Skip to main content

logicaffeine_language/parser/
quantifier.rs

1//! Quantifier parsing and scope management.
2//!
3//! This module handles determiners with quantificational force:
4//!
5//! - **Universal**: every, all, each → `∀x`
6//! - **Existential**: a, an, some → `∃x`
7//! - **Negative**: no, neither → `¬∃x` or `∀x(... → ¬...)`
8//! - **Proportional**: most, few, many → generalized quantifiers
9//! - **Definite**: the → uniqueness presupposition (ιx)
10//!
11//! # Quantifier Scope
12//!
13//! Quantifiers are assigned to scope islands during parsing. The `island_id` field
14//! tracks which island a quantifier belongs to, preventing illicit scope inversions
15//! (e.g., extracting from relative clauses).
16//!
17//! # Donkey Anaphora
18//!
19//! Indefinites in conditional antecedents or relative clauses receive universal
20//! force when bound by a pronoun in the main clause:
21//!
22//! "If a farmer owns a donkey, he beats it" → `∀x∀y((Farmer(x) ∧ Donkey(y) ∧ Owns(x,y)) → Beats(x,y))`
23
24use super::clause::ClauseParsing;
25use super::modal::ModalParsing;
26use super::noun::NounParsing;
27use super::pragmatics::PragmaticsParsing;
28use super::{IndefiniteScope, NegativeScopeMode, ParseResult, Parser};
29use crate::ast::{LogicExpr, NeoEventData, NounPhrase, QuantifierKind, Term, ThematicRole};
30use crate::drs::ReferentSource;
31use crate::drs::{Gender, Number};
32use crate::error::{ParseError, ParseErrorKind};
33use crate::lexer::Lexer;
34use crate::lexicon::{
35    get_canonical_verb, is_subsective, lookup_relational_adjective, lookup_verb_db, Definiteness,
36    Feature, Time,
37};
38use crate::token::{PresupKind, TokenType};
39use logicaffeine_base::Symbol;
40
41/// Trait for parsing quantified expressions and managing scope.
42///
43/// Provides methods for parsing quantifiers (every, some, no, most),
44/// their restrictions, and wrapping expressions with appropriate scope.
45pub trait QuantifierParsing<'a, 'ctx, 'int> {
46    /// Parses a quantified expression from a quantifier determiner.
47    fn parse_quantified(&mut self) -> ParseResult<&'a LogicExpr<'a>>;
48
49    /// The quantifier-parsing body; `parse_quantified` wraps its result with any pending
50    /// partitive-superset presupposition (§5.3).
51    fn parse_quantified_core(&mut self) -> ParseResult<&'a LogicExpr<'a>>;
52    /// Parses the restrictor clause for a quantifier.
53    fn parse_restriction(&mut self, var_name: Symbol) -> ParseResult<&'a LogicExpr<'a>>;
54    /// Builds the restriction conjunct for one pre-nominal adjective, dispatching
55    /// on its lexical class (relational/subsective/intersective). Shared by every
56    /// NP-restriction path so all paths model adjective classes identically.
57    fn adjective_restriction(
58        &mut self,
59        adj: Symbol,
60        var: Symbol,
61        noun: Symbol,
62    ) -> &'a LogicExpr<'a>;
63    /// Parses a verb phrase as the nuclear scope of a quantifier.
64    fn parse_verb_phrase_for_restriction(
65        &mut self,
66        var_name: Symbol,
67    ) -> ParseResult<&'a LogicExpr<'a>>;
68    /// Combines multiple expressions with conjunction.
69    fn combine_with_and(&self, exprs: Vec<&'a LogicExpr<'a>>) -> ParseResult<&'a LogicExpr<'a>>;
70    fn wrap_with_definiteness_full(
71        &mut self,
72        np: &NounPhrase<'a>,
73        predicate: &'a LogicExpr<'a>,
74    ) -> ParseResult<&'a LogicExpr<'a>>;
75    fn wrap_with_definiteness(
76        &mut self,
77        definiteness: Option<Definiteness>,
78        noun: Symbol,
79        predicate: &'a LogicExpr<'a>,
80    ) -> ParseResult<&'a LogicExpr<'a>>;
81    fn wrap_with_definiteness_and_adjectives(
82        &mut self,
83        definiteness: Option<Definiteness>,
84        noun: Symbol,
85        adjectives: &[Symbol],
86        predicate: &'a LogicExpr<'a>,
87    ) -> ParseResult<&'a LogicExpr<'a>>;
88    fn wrap_with_definiteness_and_adjectives_and_pps(
89        &mut self,
90        definiteness: Option<Definiteness>,
91        noun: Symbol,
92        adjectives: &[Symbol],
93        pps: &[&'a LogicExpr<'a>],
94        predicate: &'a LogicExpr<'a>,
95    ) -> ParseResult<&'a LogicExpr<'a>>;
96    fn wrap_with_definiteness_for_object(
97        &mut self,
98        definiteness: Option<Definiteness>,
99        noun: Symbol,
100        predicate: &'a LogicExpr<'a>,
101    ) -> ParseResult<&'a LogicExpr<'a>>;
102    fn substitute_pp_placeholder(
103        &mut self,
104        pp: &'a LogicExpr<'a>,
105        var: Symbol,
106    ) -> &'a LogicExpr<'a>;
107    fn substitute_constant_with_var(
108        &self,
109        expr: &'a LogicExpr<'a>,
110        constant_name: Symbol,
111        var_name: Symbol,
112    ) -> ParseResult<&'a LogicExpr<'a>>;
113    fn substitute_constant_with_var_sym(
114        &self,
115        expr: &'a LogicExpr<'a>,
116        constant_name: Symbol,
117        var_name: Symbol,
118    ) -> ParseResult<&'a LogicExpr<'a>>;
119    fn substitute_constant_with_sigma(
120        &self,
121        expr: &'a LogicExpr<'a>,
122        constant_name: Symbol,
123        sigma_term: Term<'a>,
124    ) -> ParseResult<&'a LogicExpr<'a>>;
125    /// Rewrite a relativized gap variable into a constant, so a subject's
126    /// relative-clause restriction (built over `from_var`) can be folded into a
127    /// predicate keyed on `to_const` and then re-bound uniformly by
128    /// `wrap_with_definiteness`.
129    fn substitute_variable_with_constant(
130        &self,
131        expr: &'a LogicExpr<'a>,
132        from_var: Symbol,
133        to_const: Symbol,
134    ) -> ParseResult<&'a LogicExpr<'a>>;
135    fn find_main_verb_name(&self, expr: &LogicExpr<'a>) -> Option<Symbol>;
136    fn transform_cardinal_to_group(
137        &mut self,
138        expr: &'a LogicExpr<'a>,
139    ) -> ParseResult<&'a LogicExpr<'a>>;
140    fn build_verb_neo_event(
141        &mut self,
142        verb: Symbol,
143        subject_var: Symbol,
144        object: Option<Term<'a>>,
145        modifiers: Vec<Symbol>,
146    ) -> &'a LogicExpr<'a>;
147    /// Parse a copula PP complement under a quantifier — "is in Florida or in
148    /// Maine" → In(subj,Florida) ∨ In(subj,Maine), `subj_var` being the bound
149    /// variable. Captures the or-coordination ("or in B" repeats the preposition,
150    /// "or B" reuses it) that the backtracking fallback path otherwise drops.
151    fn parse_copula_pp_complement(&mut self, subj_var: Symbol) -> ParseResult<&'a LogicExpr<'a>>;
152}
153
154impl<'a, 'ctx, 'int> QuantifierParsing<'a, 'ctx, 'int> for Parser<'a, 'ctx, 'int> {
155    fn parse_copula_pp_complement(&mut self, subj_var: Symbol) -> ParseResult<&'a LogicExpr<'a>> {
156        let prep_sym = match self.advance().kind {
157            TokenType::Preposition(s) => s,
158            _ => unreachable!("guarded by check_preposition"),
159        };
160        let saved_ctx = self.nominal_np_context;
161        self.nominal_np_context = true;
162        let obj_res = self.parse_noun_phrase(true);
163        self.nominal_np_context = saved_ctx;
164        let obj = obj_res?;
165        let first: &'a LogicExpr<'a> = self.ctx.exprs.alloc(LogicExpr::Predicate {
166            name: prep_sym,
167            args: self
168                .ctx
169                .terms
170                .alloc_slice([Term::Variable(subj_var), Term::Constant(obj.noun)]),
171            world: None,
172        });
173        let mut base = self.attach_pp_object_modifiers(first, &obj);
174        while self.check(&TokenType::Or) {
175            let cp = self.checkpoint();
176            self.advance(); // "or"
177            let disj_prep = if self.check_preposition() && !self.check_by_preposition() {
178                match self.advance().kind {
179                    TokenType::Preposition(s) => s,
180                    _ => prep_sym,
181                }
182            } else {
183                prep_sym
184            };
185            if !(self.check_content_word()
186                || self.check_number()
187                || matches!(self.peek().kind, TokenType::Article(_)))
188            {
189                self.restore(cp);
190                break;
191            }
192            let saved = self.nominal_np_context;
193            self.nominal_np_context = true;
194            let disj_obj_res = self.parse_noun_phrase(true);
195            self.nominal_np_context = saved;
196            let disj_obj = disj_obj_res?;
197            let disj: &'a LogicExpr<'a> = self.ctx.exprs.alloc(LogicExpr::Predicate {
198                name: disj_prep,
199                args: self
200                    .ctx
201                    .terms
202                    .alloc_slice([Term::Variable(subj_var), Term::Constant(disj_obj.noun)]),
203                world: None,
204            });
205            let disj = self.attach_pp_object_modifiers(disj, &disj_obj);
206            base = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
207                left: base,
208                op: TokenType::Or,
209                right: disj,
210            });
211        }
212        Ok(base)
213    }
214
215    fn parse_quantified(&mut self) -> ParseResult<&'a LogicExpr<'a>> {
216        // The specialized quantified-VP grammar below covers many frames but
217        // not all of them. A parse that stops mid-clause silently drops the
218        // remainder's meaning, so when it under-consumes (or fails), re-parse
219        // the clause delegating the VP to the full predicate parser. The
220        // specialized result is kept whenever the delegation does no better.
221        let cp = self.checkpoint();
222        let core = self.parse_quantified_core();
223        let core_complete = core.is_ok() && self.at_clause_boundary();
224        let result = if core_complete {
225            core?
226        } else {
227            let core_end = self.checkpoint();
228            let core_partitive = self.pending_partitive.take();
229            self.restore(cp);
230            match self.parse_quantified_delegating() {
231                Ok(r) if self.at_clause_boundary() => r,
232                _ => match core {
233                    Ok(r) => {
234                        self.restore(core_end);
235                        self.pending_partitive = core_partitive;
236                        r
237                    }
238                    Err(e) => return Err(e),
239                },
240            }
241        };
242        // §5.3: a partitive "of the [Num]" frame presupposes a salient set of that
243        // cardinality. Surface it as `assertion [Presup: ∃=n x Restriction(x)]` rather
244        // than discarding the superset.
245        if let Some((n, restriction, var)) = self.pending_partitive.take() {
246            let superset = self.ctx.exprs.alloc(LogicExpr::Quantifier {
247                kind: QuantifierKind::Cardinal(n),
248                variable: var,
249                body: restriction,
250                island_id: self.current_island,
251            });
252            return Ok(self.ctx.exprs.alloc(LogicExpr::Presupposition {
253                assertion: result,
254                presupposition: superset,
255            }));
256        }
257        Ok(result)
258    }
259
260    fn parse_quantified_core(&mut self) -> ParseResult<&'a LogicExpr<'a>> {
261        let quantifier_token = self.previous().kind.clone();
262        let var_name = self.next_var_name();
263
264        // Track if we're inside a "No" quantifier - referents introduced here
265        // are inaccessible for cross-sentence anaphora
266        let was_in_negative_quantifier = self.in_negative_quantifier;
267        if matches!(quantifier_token, TokenType::No) {
268            self.in_negative_quantifier = true;
269        }
270
271        // Partitive: "Two of the three students passed.", "Most of the students
272        // passed." The "of the [Num]" frame restricts the quantifier to a salient
273        // presupposed definite set. Consume the frame so the quantifier ranges over
274        // the head noun normally; the leading cardinal/proportion is the count, the
275        // optional inner cardinal is the presupposed superset size.
276        let mut partitive_superset: Option<u32> = None;
277        if (quantifier_token.is_generalized_quantifier()
278            || matches!(
279                quantifier_token,
280                TokenType::Cardinal(_)
281                    | TokenType::Some
282                    | TokenType::AtLeast(_)
283                    | TokenType::AtMost(_)
284            ))
285            && self.check_preposition_is("of")
286            && self.current + 1 < self.tokens.len()
287            && matches!(self.tokens[self.current + 1].kind, TokenType::Article(_))
288        {
289            self.advance(); // consume "of"
290            self.advance(); // consume "the"
291            if let TokenType::Cardinal(n) = self.peek().kind {
292                partitive_superset = Some(n);
293                self.advance(); // consume the superset cardinal ("three")
294            }
295        }
296        // "At most one of X, Y, and Z is P" — counting quantifier with explicit list
297        if matches!(
298            quantifier_token,
299            TokenType::AtMost(_) | TokenType::AtLeast(_) | TokenType::Cardinal(_)
300        ) && self.check_preposition_is("of")
301        {
302            self.advance(); // consume "of"
303
304            // Parse comma-separated list of identifiers: "grant0, grant1, and grant2"
305            let mut signal_names: Vec<Symbol> = Vec::new();
306            loop {
307                let name = self.consume_content_word()?;
308                signal_names.push(name);
309
310                if self.check(&TokenType::Comma) {
311                    self.advance(); // consume ","
312                                    // Skip optional "and" after comma: "X, Y, and Z"
313                    if self.check(&TokenType::And) {
314                        self.advance();
315                    }
316                } else if self.check(&TokenType::And) {
317                    self.advance(); // consume "and" (two-element: "X and Y")
318                } else {
319                    break;
320                }
321            }
322
323            // Now parse the predicate: "is asserted", "is valid", etc.
324            // In hardware context, the predicate is implicit — what matters
325            // is each signal name being high/low. Consume but don't use.
326            let mut is_negated = false;
327            if self.check(&TokenType::Is) || self.check(&TokenType::Are) {
328                self.advance(); // consume copula
329                is_negated = self.check(&TokenType::Not);
330                if is_negated {
331                    self.advance();
332                }
333                // Consume the predicate adjective/verb (e.g., "asserted", "valid")
334                let _ = self.consume_content_word();
335                // Consume optional trailing "at any time"
336                while self.check_preposition_is("at") {
337                    self.advance();
338                    if self.check(&TokenType::Any) {
339                        self.advance();
340                    }
341                    if self.check_content_word() {
342                        self.advance();
343                    }
344                }
345            }
346
347            // Build the body: each signal as an Atom, joined by OR
348            // SVA synthesis maps Atom(sig) → signal name directly
349            let mut signal_exprs: Vec<&'a LogicExpr<'a>> = Vec::new();
350            for &sig in &signal_names {
351                let atom: &'a LogicExpr<'a> = self.ctx.exprs.alloc(LogicExpr::Atom(sig));
352                let sig_expr = if is_negated {
353                    self.ctx.exprs.alloc(LogicExpr::UnaryOp {
354                        op: TokenType::Not,
355                        operand: atom,
356                    })
357                } else {
358                    atom
359                };
360                signal_exprs.push(sig_expr);
361            }
362
363            let body = if signal_exprs.len() == 1 {
364                signal_exprs[0]
365            } else {
366                let mut combined = signal_exprs[0];
367                for &expr in &signal_exprs[1..] {
368                    combined = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
369                        left: combined,
370                        op: TokenType::Or,
371                        right: expr,
372                    });
373                }
374                combined
375            };
376
377            let kind = match quantifier_token {
378                TokenType::AtMost(n) => QuantifierKind::AtMost(n),
379                TokenType::AtLeast(n) => QuantifierKind::AtLeast(n),
380                TokenType::Cardinal(n) => QuantifierKind::Cardinal(n),
381                _ => unreachable!(),
382            };
383
384            self.in_negative_quantifier = was_in_negative_quantifier;
385
386            return Ok(self.ctx.exprs.alloc(LogicExpr::Quantifier {
387                kind,
388                variable: var_name,
389                body,
390                island_id: self.current_island,
391            }));
392        }
393
394        let subject_pred = self.parse_restriction(var_name)?;
395
396        // §5.3: stash the partitive superset now that the restriction predicate exists; the
397        // `parse_quantified` wrapper turns it into a presupposed `∃=n x Restriction(x)`.
398        if let Some(n) = partitive_superset {
399            self.pending_partitive = Some((n, subject_pred, var_name));
400        }
401
402        if self.check_modal() {
403            use crate::ast::ModalFlavor;
404
405            self.advance();
406            let vector = self.token_to_vector(&self.previous().kind.clone());
407            let verb = self.consume_content_word()?;
408
409            // Parse object if present (e.g., "can enter the room" -> room is object)
410            let obj_term = if self.check_content_word() || self.check_article() {
411                let obj_np = self.parse_noun_phrase(false)?;
412                Some(self.noun_phrase_to_term(&obj_np))
413            } else {
414                None
415            };
416
417            // Collect any trailing adverbs
418            let modifiers = self.collect_adverbs();
419            let verb_pred = self.build_verb_neo_event(verb, var_name, obj_term, modifiers);
420
421            // Determine quantifier kind first (shared by both branches)
422            let kind = self.determiner_quantifier(&quantifier_token)?;
423
424            // Branch on modal flavor for scope handling
425            if vector.flavor == ModalFlavor::Root {
426                // === NARROW SCOPE (De Re) ===
427                // Root modals (can, must, should) attach to the predicate inside the quantifier
428                // "Some birds can fly" → ∃x(Bird(x) ∧ ◇Fly(x))
429
430                // Wrap the verb predicate in the modal
431                let modal_verb = self.ctx.exprs.alloc(LogicExpr::Modal {
432                    vector,
433                    operand: verb_pred,
434                });
435
436                let body = self.determiner_body(&quantifier_token, subject_pred, modal_verb)?;
437
438                // Build quantifier (modal is inside)
439                let mut result = self.ctx.exprs.alloc(LogicExpr::Quantifier {
440                    kind,
441                    variable: var_name,
442                    body,
443                    island_id: self.current_island,
444                });
445
446                // Process donkey bindings for indefinites in restrictions (e.g., "who lacks a key")
447                for (_noun, donkey_var, used, wide_neg) in self.donkey_bindings.iter().rev() {
448                    if *used {
449                        // Donkey anaphora: wrap with ∀ at outer scope
450                        result = self.ctx.exprs.alloc(LogicExpr::Quantifier {
451                            kind: QuantifierKind::Universal,
452                            variable: *donkey_var,
453                            body: result,
454                            island_id: self.current_island,
455                        });
456                    } else {
457                        // Non-donkey: wrap with ∃ INSIDE the restriction
458                        result = self.wrap_donkey_in_restriction(result, *donkey_var, *wide_neg);
459                    }
460                }
461                self.donkey_bindings.clear();
462
463                self.in_negative_quantifier = was_in_negative_quantifier;
464                return Ok(result);
465            } else {
466                // === WIDE SCOPE (De Dicto) ===
467                // Epistemic modals (might, may) wrap the entire quantifier
468                // "Some unicorns might exist" → ◇∃x(Unicorn(x) ∧ Exist(x))
469
470                let body = self.determiner_body(&quantifier_token, subject_pred, verb_pred)?;
471
472                let mut result = self.ctx.exprs.alloc(LogicExpr::Quantifier {
473                    kind,
474                    variable: var_name,
475                    body,
476                    island_id: self.current_island,
477                });
478
479                // Process donkey bindings for indefinites in restrictions (e.g., "who lacks a key")
480                for (_noun, donkey_var, used, wide_neg) in self.donkey_bindings.iter().rev() {
481                    if *used {
482                        // Donkey anaphora: wrap with ∀ at outer scope
483                        result = self.ctx.exprs.alloc(LogicExpr::Quantifier {
484                            kind: QuantifierKind::Universal,
485                            variable: *donkey_var,
486                            body: result,
487                            island_id: self.current_island,
488                        });
489                    } else {
490                        // Non-donkey: wrap with ∃ INSIDE the restriction
491                        result = self.wrap_donkey_in_restriction(result, *donkey_var, *wide_neg);
492                    }
493                }
494                self.donkey_bindings.clear();
495
496                // Wrap the entire quantifier in the modal
497                self.in_negative_quantifier = was_in_negative_quantifier;
498                return Ok(self.ctx.exprs.alloc(LogicExpr::Modal {
499                    vector,
500                    operand: result,
501                }));
502            }
503        }
504
505        if self.check_auxiliary() {
506            let aux_token = self.advance();
507            let aux_time = if let TokenType::Auxiliary(time) = aux_token.kind.clone() {
508                time
509            } else {
510                Time::None
511            };
512            self.pending_time = Some(aux_time);
513
514            let is_negated = self.match_token(&[TokenType::Not]);
515            if is_negated {
516                self.negative_depth += 1;
517            }
518
519            // A polarity adverb between the auxiliary and the verb ("will EVER be
520            // used", "would NEVER be seen") is an NPI licensed by the negative
521            // quantifier — vacuous to the truth conditions here, so skip it.
522            while self.check(&TokenType::Ever) {
523                self.advance();
524            }
525
526            if self.check_verb() {
527                let verb = self.consume_verb();
528
529                // Passive auxiliary "will/would BE used": the copula `be`/`been` is
530                // followed by a past-participle verb that is the real predicate — its
531                // lemma fills the Theme ("will be USED" → Be(e) ∧ Theme(e, Use)),
532                // mirroring the non-quantified passive path.
533                let verb_lower = self.interner.resolve(verb).to_lowercase();
534                let obj_term = if matches!(verb_lower.as_str(), "be" | "been") && self.check_verb()
535                {
536                    Some(Term::Constant(self.consume_verb()))
537                } else {
538                    None
539                };
540
541                // Convert aux_time to modifier
542                let mut modifiers = match aux_time {
543                    Time::Past => vec![self.interner.intern("Past")],
544                    Time::Future => vec![self.interner.intern("Future")],
545                    _ => vec![],
546                };
547                // Manner adverbs after the participle ("were running quickly").
548                modifiers.extend(self.collect_adverbs());
549
550                // Frequency comparative "... used MORE THAN ONCE": Comparative +
551                // "than" + count noun. Absorb it as an event modifier (the exact
552                // count is immaterial to the bijection a grid eliminates).
553                if self.check_comparative() {
554                    self.advance(); // "more"
555                    if self.check(&TokenType::Than) {
556                        self.advance();
557                    }
558                    if self.check_content_word() || self.check_number() {
559                        self.advance(); // the count word ("once", "twice", a number)
560                    }
561                    modifiers.push(self.interner.intern("MoreThanOnce"));
562                }
563
564                let verb_pred = self.build_verb_neo_event(verb, var_name, obj_term, modifiers);
565
566                let maybe_negated = if is_negated {
567                    self.negative_depth -= 1;
568                    self.ctx.exprs.alloc(LogicExpr::UnaryOp {
569                        op: TokenType::Not,
570                        operand: verb_pred,
571                    })
572                } else {
573                    verb_pred
574                };
575
576                let body = self.determiner_body(&quantifier_token, subject_pred, maybe_negated)?;
577
578                let kind = self.determiner_quantifier(&quantifier_token)?;
579
580                self.in_negative_quantifier = was_in_negative_quantifier;
581                return Ok(self.ctx.exprs.alloc(LogicExpr::Quantifier {
582                    kind,
583                    variable: var_name,
584                    body,
585                    island_id: self.current_island,
586                }));
587            }
588        }
589
590        // Only trigger presupposition if followed by gerund complement
591        if self.check_presup_trigger() && self.is_followed_by_gerund() {
592            let presup_kind = match self.advance().kind {
593                TokenType::PresupTrigger(kind) => kind,
594                TokenType::Verb { lemma, .. } => {
595                    let s = self.interner.resolve(lemma).to_lowercase();
596                    crate::lexicon::lookup_presup_trigger(&s)
597                        .expect("Lexicon mismatch: Verb flagged as trigger but lookup failed")
598                }
599                _ => panic!("Expected presupposition trigger"),
600            };
601
602            let complement = if self.check_verb() {
603                let verb = self.consume_verb();
604                let modifiers = self.collect_adverbs();
605                self.build_verb_neo_event(verb, var_name, None, modifiers)
606            } else {
607                let unknown = self.interner.intern("?");
608                self.ctx.exprs.alloc(LogicExpr::Atom(unknown))
609            };
610
611            let verb_pred = match presup_kind {
612                PresupKind::Stop => self.ctx.exprs.alloc(LogicExpr::UnaryOp {
613                    op: TokenType::Not,
614                    operand: complement,
615                }),
616                PresupKind::Start | PresupKind::Continue => complement,
617                PresupKind::Regret | PresupKind::Realize | PresupKind::Know => complement,
618            };
619
620            let body = self.determiner_body(&quantifier_token, subject_pred, verb_pred)?;
621
622            let kind = self.determiner_quantifier(&quantifier_token)?;
623
624            self.in_negative_quantifier = was_in_negative_quantifier;
625            return Ok(self.ctx.exprs.alloc(LogicExpr::Quantifier {
626                kind,
627                variable: var_name,
628                body,
629                island_id: self.current_island,
630            }));
631        }
632
633        if self.check_verb() {
634            let verb = self.consume_verb();
635            let mut args = vec![Term::Variable(var_name)];
636
637            if self.check_pronoun() {
638                let token = self.peek().clone();
639                if let TokenType::Pronoun { gender, .. } = token.kind {
640                    self.advance();
641                    if let Some(donkey_var) = self.resolve_donkey_pronoun(gender) {
642                        args.push(Term::Variable(donkey_var));
643                    } else {
644                        let resolved = self.resolve_pronoun(gender, Number::Singular)?;
645                        let term = match resolved {
646                            super::ResolvedPronoun::Variable(s) => Term::Variable(s),
647                            super::ResolvedPronoun::Constant(s) => Term::Constant(s),
648                        };
649                        args.push(term);
650                    }
651                }
652            } else if self.check_npi_object() {
653                let npi_token = self.advance().kind.clone();
654                let obj_var = self.next_var_name();
655
656                let restriction_name = match npi_token {
657                    TokenType::Anything => "Thing",
658                    TokenType::Anyone => "Person",
659                    _ => "Thing",
660                };
661
662                let restriction_sym = self.interner.intern(restriction_name);
663                let obj_restriction = self.ctx.exprs.alloc(LogicExpr::Predicate {
664                    name: restriction_sym,
665                    args: self.ctx.terms.alloc_slice([Term::Variable(obj_var)]),
666                    world: None,
667                });
668
669                let npi_modifiers = self.collect_adverbs();
670                let verb_with_obj = self.build_verb_neo_event(
671                    verb,
672                    var_name,
673                    Some(Term::Variable(obj_var)),
674                    npi_modifiers,
675                );
676
677                let npi_body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
678                    left: obj_restriction,
679                    op: TokenType::And,
680                    right: verb_with_obj,
681                });
682
683                let npi_quantified = self.ctx.exprs.alloc(LogicExpr::Quantifier {
684                    kind: QuantifierKind::Existential,
685                    variable: obj_var,
686                    body: npi_body,
687                    island_id: self.current_island,
688                });
689
690                let negated_npi = self.ctx.exprs.alloc(LogicExpr::UnaryOp {
691                    op: TokenType::Not,
692                    operand: npi_quantified,
693                });
694
695                // `no` licenses the NPI, whose negation is the determiner's own.
696                let body: &'a LogicExpr<'a> = if matches!(quantifier_token, TokenType::No) {
697                    self.ctx.exprs.alloc(LogicExpr::BinaryOp {
698                        left: subject_pred,
699                        op: TokenType::Implies,
700                        right: negated_npi,
701                    })
702                } else {
703                    self.determiner_body(&quantifier_token, subject_pred, negated_npi)?
704                };
705
706                let kind = self.determiner_quantifier(&quantifier_token)?;
707
708                self.in_negative_quantifier = was_in_negative_quantifier;
709                return Ok(self.ctx.exprs.alloc(LogicExpr::Quantifier {
710                    kind,
711                    variable: var_name,
712                    body,
713                    island_id: self.current_island,
714                }));
715            } else if self.check_quantifier()
716                || self.check_article()
717                || self.check_possessive_pronoun()
718            {
719                let obj_quantifier = if self.check_possessive_pronoun() {
720                    // Possessive NP object ("his dog"): parse_noun_phrase
721                    // consumes the possessor; no quantifier wrapper.
722                    None
723                } else if self.check_quantifier() {
724                    Some(self.advance().kind.clone())
725                } else {
726                    let art = self.advance().kind.clone();
727                    if let TokenType::Article(def) = art {
728                        if def == Definiteness::Indefinite {
729                            Some(TokenType::Some)
730                        } else {
731                            None
732                        }
733                    } else {
734                        None
735                    }
736                };
737
738                let object = self.parse_noun_phrase(false)?;
739
740                if let Some(obj_q) = obj_quantifier {
741                    let obj_var = self.next_var_name();
742
743                    // Introduce object referent in DRS for cross-sentence anaphora (telescoping)
744                    // BUT: If inside "No X" quantifier, mark with NegationScope to block accessibility
745                    let obj_gender = Self::infer_noun_gender(self.interner.resolve(object.noun));
746                    let obj_number = if Self::is_plural_noun(self.interner.resolve(object.noun)) {
747                        Number::Plural
748                    } else {
749                        Number::Singular
750                    };
751                    if self.in_negative_quantifier {
752                        self.drs.introduce_referent_with_source(
753                            obj_var,
754                            object.noun,
755                            obj_gender,
756                            obj_number,
757                            ReferentSource::NegationScope,
758                        );
759                    } else {
760                        self.drs
761                            .introduce_referent(obj_var, object.noun, obj_gender, obj_number);
762                    }
763
764                    let mut obj_restriction: &'a LogicExpr<'a> =
765                        self.ctx.exprs.alloc(LogicExpr::Predicate {
766                            name: object.noun,
767                            args: self.ctx.terms.alloc_slice([Term::Variable(obj_var)]),
768                            world: None,
769                        });
770                    // The object's adjectives ("a RED book") and PP restrictors
771                    // ("a maximum range OF 475 ft") are part of its description —
772                    // dropping them is a meaning-loss parse.
773                    for &adj in object.adjectives {
774                        let adj_pred = self.adjective_restriction(adj, obj_var, object.noun);
775                        obj_restriction = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
776                            left: obj_restriction,
777                            op: TokenType::And,
778                            right: adj_pred,
779                        });
780                    }
781                    for pp in object.pps {
782                        let pp_sub = self.substitute_pp_placeholder(pp, obj_var);
783                        obj_restriction = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
784                            left: obj_restriction,
785                            op: TokenType::And,
786                            right: pp_sub,
787                        });
788                    }
789
790                    let obj_modifiers = self.collect_adverbs();
791                    let verb_with_obj = self.build_verb_neo_event(
792                        verb,
793                        var_name,
794                        Some(Term::Variable(obj_var)),
795                        obj_modifiers,
796                    );
797
798                    let obj_quantified =
799                        self.quantify_argument(&obj_q, obj_var, obj_restriction, verb_with_obj);
800
801                    let subj_kind = self.determiner_quantifier(&quantifier_token)?;
802
803                    let subj_body =
804                        self.determiner_body(&quantifier_token, subject_pred, obj_quantified)?;
805
806                    self.in_negative_quantifier = was_in_negative_quantifier;
807                    let mut result = self.ctx.exprs.alloc(LogicExpr::Quantifier {
808                        kind: subj_kind,
809                        variable: var_name,
810                        body: subj_body,
811                        island_id: self.current_island,
812                    });
813                    // Close any donkey-anaphora indefinites from the subject's
814                    // relative clause (e.g. "a donkey" in "Every farmer who owns
815                    // a donkey feeds every animal"). This quantified-object path
816                    // previously returned WITHOUT the closure run by the main VP
817                    // path, leaving the donkey variable FREE in the formula.
818                    for (_noun, donkey_var, used, wide_neg) in self.donkey_bindings.iter().rev() {
819                        if *used {
820                            result = self.ctx.exprs.alloc(LogicExpr::Quantifier {
821                                kind: QuantifierKind::Universal,
822                                variable: *donkey_var,
823                                body: result,
824                                island_id: self.current_island,
825                            });
826                        } else {
827                            result =
828                                self.wrap_donkey_in_restriction(result, *donkey_var, *wide_neg);
829                        }
830                    }
831                    self.donkey_bindings.clear();
832                    return Ok(result);
833                } else {
834                    args.push(Term::Constant(object.noun));
835                }
836            } else if self.check_content_word() {
837                let object = self.parse_noun_phrase(false)?;
838                args.push(Term::Constant(object.noun));
839            }
840
841            // Extract object term from args if present (args[0] is subject, args[1] is object)
842            let obj_term = if args.len() > 1 {
843                Some(args.remove(1))
844            } else {
845                None
846            };
847            // Collect any trailing adverbs (e.g., "bark loudly")
848            let modifiers = self.collect_adverbs();
849            let verb_pred = self.build_verb_neo_event(verb, var_name, obj_term, modifiers);
850
851            let body = self.determiner_body(&quantifier_token, subject_pred, verb_pred)?;
852
853            let kind = self.determiner_quantifier(&quantifier_token)?;
854
855            let mut result = self.ctx.exprs.alloc(LogicExpr::Quantifier {
856                kind,
857                variable: var_name,
858                body,
859                island_id: self.current_island,
860            });
861
862            for (_noun, donkey_var, used, wide_neg) in self.donkey_bindings.iter().rev() {
863                if *used {
864                    // Donkey anaphora: wrap with ∀ at outer scope
865                    result = self.ctx.exprs.alloc(LogicExpr::Quantifier {
866                        kind: QuantifierKind::Universal,
867                        variable: *donkey_var,
868                        body: result,
869                        island_id: self.current_island,
870                    });
871                } else {
872                    // Non-donkey: wrap with ∃ INSIDE the restriction
873                    result = self.wrap_donkey_in_restriction(result, *donkey_var, *wide_neg);
874                }
875            }
876            self.donkey_bindings.clear();
877
878            self.in_negative_quantifier = was_in_negative_quantifier;
879            return Ok(result);
880        }
881
882        // Handle do-support: "every X does not hold" → ¬Hold(x)
883        if self.check(&TokenType::Does) || self.check(&TokenType::Do) {
884            self.advance(); // consume "does"/"do"
885            let negative = self.match_token(&[TokenType::Not]);
886            // The verb after "does not" becomes the predicate
887            let verb_sym = self.consume_verb();
888            let predicate_expr = self.ctx.exprs.alloc(LogicExpr::Predicate {
889                name: verb_sym,
890                args: self.ctx.terms.alloc_slice([Term::Variable(var_name)]),
891                world: None,
892            });
893            let final_predicate = if negative {
894                self.ctx.exprs.alloc(LogicExpr::UnaryOp {
895                    op: TokenType::Not,
896                    operand: predicate_expr,
897                })
898            } else {
899                predicate_expr
900            };
901
902            let body = self.determiner_body(&quantifier_token, subject_pred, final_predicate)?;
903
904            let result = self.ctx.exprs.alloc(LogicExpr::Quantifier {
905                kind: self.determiner_quantifier(&quantifier_token)?,
906                variable: var_name,
907                body: body,
908                island_id: self.current_island,
909            });
910            self.in_negative_quantifier = was_in_negative_quantifier;
911            return Ok(result);
912        }
913
914        self.consume_copula()?;
915
916        let negative = self.match_token(&[TokenType::Not]);
917
918        // Copula PP complement under a quantifier: "Every trip is in Florida (or in
919        // Maine)" → ∀x(Trip(x) → In(x,Florida) [∨ In(x,Maine)]) — the domain-closure
920        // a logic-grid bijection eliminates over. A leading preposition makes
921        // parse_noun_phrase fail, dropping the clause to a backtracking path that
922        // loses the or-coordination AND any trailing PP, so handle the PP — with its
923        // disjunction — directly here.
924        let is_pp_complement = self.check_preposition() && !self.check_by_preposition();
925        let mut final_predicate = if is_pp_complement {
926            let pp = self.parse_copula_pp_complement(var_name)?;
927            if negative {
928                self.ctx.exprs.alloc(LogicExpr::UnaryOp {
929                    op: TokenType::Not,
930                    operand: pp,
931                })
932            } else {
933                pp
934            }
935        } else {
936            let predicate_np = self.parse_noun_phrase(true)?;
937            let predicate_expr = self.ctx.exprs.alloc(LogicExpr::Predicate {
938                name: predicate_np.noun,
939                args: self.ctx.terms.alloc_slice([Term::Variable(var_name)]),
940                world: None,
941            });
942            if negative {
943                self.ctx.exprs.alloc(LogicExpr::UnaryOp {
944                    op: TokenType::Not,
945                    operand: predicate_expr,
946                })
947            } else {
948                predicate_expr
949            }
950        };
951
952        // Disjunctive copula complement: "is red or blue", "is red, blue, or
953        // green". Each disjunct is the same predicate form applied to the SAME
954        // bound variable, so the `or` stays INSIDE the consequent (distributing
955        // the variable) rather than being lifted to sentence level. A comma list
956        // ("A, B, or C") coordinates with `or`; the trailing `or` before the
957        // last item is optional after a comma. A `Comma` that is NOT part of such
958        // a list (no following predicate complement) is left for the caller.
959        // (The PP-complement case consumed its own or-coordination above.)
960        while !is_pp_complement {
961            let is_or = self.check(&TokenType::Or);
962            let is_comma_list = self.check(&TokenType::Comma)
963                && matches!(
964                    self.tokens.get(self.current + 1).map(|t| &t.kind),
965                    Some(TokenType::Adjective(_))
966                        | Some(TokenType::Noun(_))
967                        | Some(TokenType::ProperName(_))
968                        | Some(TokenType::Or)
969                );
970            if !is_or && !is_comma_list {
971                break;
972            }
973            if is_comma_list {
974                self.advance(); // consume ","
975                                // "A, B, or C": drop the coordinating "or"/"and" after the comma.
976                if self.check(&TokenType::Or) || self.check(&TokenType::And) {
977                    self.advance();
978                }
979            } else {
980                self.advance(); // consume "or"
981            }
982
983            let disj_negative = self.match_token(&[TokenType::Not]);
984            let disj_np = self.parse_noun_phrase(true)?;
985            let disj_pred: &'a LogicExpr<'a> = self.ctx.exprs.alloc(LogicExpr::Predicate {
986                name: disj_np.noun,
987                args: self.ctx.terms.alloc_slice([Term::Variable(var_name)]),
988                world: None,
989            });
990            let disj_pred = if disj_negative {
991                self.ctx.exprs.alloc(LogicExpr::UnaryOp {
992                    op: TokenType::Not,
993                    operand: disj_pred,
994                })
995            } else {
996                disj_pred
997            };
998            final_predicate = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
999                left: final_predicate,
1000                op: TokenType::Or,
1001                right: disj_pred,
1002            });
1003        }
1004
1005        let body = self.determiner_body(&quantifier_token, subject_pred, final_predicate)?;
1006
1007        let kind = self.determiner_quantifier(&quantifier_token)?;
1008
1009        let mut result = self.ctx.exprs.alloc(LogicExpr::Quantifier {
1010            kind,
1011            variable: var_name,
1012            body,
1013            island_id: self.current_island,
1014        });
1015
1016        for (_noun, donkey_var, used, wide_neg) in self.donkey_bindings.iter().rev() {
1017            if *used {
1018                // Donkey anaphora: wrap with ∀ at outer scope
1019                result = self.ctx.exprs.alloc(LogicExpr::Quantifier {
1020                    kind: QuantifierKind::Universal,
1021                    variable: *donkey_var,
1022                    body: result,
1023                    island_id: self.current_island,
1024                });
1025            } else {
1026                // Non-donkey: wrap with ∃ INSIDE the restriction
1027                result = self.wrap_donkey_in_restriction(result, *donkey_var, *wide_neg);
1028            }
1029        }
1030        self.donkey_bindings.clear();
1031
1032        self.in_negative_quantifier = was_in_negative_quantifier;
1033        Ok(result)
1034    }
1035
1036    /// Build the restriction conjunct contributed by a pre-nominal adjective,
1037    /// dispatching on the adjective's lexical class. This is the single shared
1038    /// site every NP-restriction path routes through, so the four classes are
1039    /// modeled identically everywhere (universal, indefinite, definite, copular):
1040    ///
1041    /// - **Relational / pertainymic** (lexicon `relational`): predicate of a
1042    ///   kind by default — `Rel(x, ^Base)` (no ∃) — or, at `level: Instance`,
1043    ///   an existential over a base-noun individual — `∃y(Base(y) ∧ Rel(x, y))`.
1044    ///   (McNally & Boleda 2004.)
1045    /// - **Subsective**: `Adj(x, ^Noun)` — graded against the head-noun kind.
1046    /// - **Intersective / other** (incl. NonIntersective, whose privative
1047    ///   meaning is supplied later by the axiom layer): flat `Adj(x)`.
1048    fn adjective_restriction(
1049        &mut self,
1050        adj: Symbol,
1051        var: Symbol,
1052        noun: Symbol,
1053    ) -> &'a LogicExpr<'a> {
1054        let adj_str = self.interner.resolve(adj).to_lowercase();
1055
1056        if let Some((base, relation, level)) = lookup_relational_adjective(&adj_str) {
1057            let base_sym = self.interner.intern(base);
1058            let rel_sym = self.interner.intern(relation);
1059            if level == "Instance" {
1060                // ∃y( Base(y) ∧ Rel(x, y) )
1061                let y = self.next_var_name();
1062                let base_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
1063                    name: base_sym,
1064                    args: self.ctx.terms.alloc_slice([Term::Variable(y)]),
1065                    world: None,
1066                });
1067                let rel_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
1068                    name: rel_sym,
1069                    args: self
1070                        .ctx
1071                        .terms
1072                        .alloc_slice([Term::Variable(var), Term::Variable(y)]),
1073                    world: None,
1074                });
1075                let body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1076                    left: base_pred,
1077                    op: TokenType::And,
1078                    right: rel_pred,
1079                });
1080                return self.ctx.exprs.alloc(LogicExpr::Quantifier {
1081                    kind: QuantifierKind::Existential,
1082                    variable: y,
1083                    body,
1084                    island_id: self.current_island,
1085                });
1086            }
1087            // kind-level (default): Rel(x, ^Base)
1088            return self.ctx.exprs.alloc(LogicExpr::Predicate {
1089                name: rel_sym,
1090                args: self
1091                    .ctx
1092                    .terms
1093                    .alloc_slice([Term::Variable(var), Term::Kind(base_sym)]),
1094                world: None,
1095            });
1096        }
1097
1098        if is_subsective(&adj_str) {
1099            return self.ctx.exprs.alloc(LogicExpr::Predicate {
1100                name: adj,
1101                args: self
1102                    .ctx
1103                    .terms
1104                    .alloc_slice([Term::Variable(var), Term::Intension(noun)]),
1105                world: None,
1106            });
1107        }
1108
1109        self.ctx.exprs.alloc(LogicExpr::Predicate {
1110            name: adj,
1111            args: self.ctx.terms.alloc_slice([Term::Variable(var)]),
1112            world: None,
1113        })
1114    }
1115
1116    fn parse_restriction(&mut self, var_name: Symbol) -> ParseResult<&'a LogicExpr<'a>> {
1117        // Collect leading adjectives, then consume the head noun. The adjective
1118        // predicate forms (subsective `Adj(x, ^Noun)`, relational expansions)
1119        // need the head noun, so the noun is resolved before they are emitted.
1120        let mut adj_syms: Vec<Symbol> = Vec::new();
1121
1122        loop {
1123            if self.is_at_end() {
1124                break;
1125            }
1126
1127            let is_adjective = matches!(self.peek().kind, TokenType::Adjective(_));
1128            if !is_adjective {
1129                break;
1130            }
1131
1132            let next_is_content = if self.current + 1 < self.tokens.len() {
1133                matches!(
1134                    self.tokens[self.current + 1].kind,
1135                    TokenType::Noun(_) | TokenType::Adjective(_) | TokenType::ProperName(_)
1136                )
1137            } else {
1138                false
1139            };
1140
1141            if next_is_content {
1142                if let TokenType::Adjective(adj) = self.advance().kind.clone() {
1143                    adj_syms.push(adj);
1144                }
1145            } else {
1146                break;
1147            }
1148        }
1149
1150        let mut noun = self.consume_content_word()?;
1151        // Noun-noun compound restrictor ("Every chess game", "Each fire truck"):
1152        // join consecutive nouns into one symbol, mirroring parse_noun_phrase's
1153        // head compounding, so "Every chess game" doesn't strand "game".
1154        while let TokenType::Noun(next) = self.peek().kind {
1155            self.advance();
1156            noun = self.interner.intern(&format!(
1157                "{}_{}",
1158                self.interner.resolve(noun),
1159                self.interner.resolve(next)
1160            ));
1161        }
1162
1163        let mut conditions: Vec<&'a LogicExpr<'a>> = Vec::new();
1164        for adj in &adj_syms {
1165            let adj_pred = self.adjective_restriction(*adj, var_name, noun);
1166            conditions.push(adj_pred);
1167        }
1168        conditions.push(self.ctx.exprs.alloc(LogicExpr::Predicate {
1169            name: noun,
1170            args: self.ctx.terms.alloc_slice([Term::Variable(var_name)]),
1171            world: None,
1172        }));
1173
1174        // PP post-modifiers on the restrictor head ("every dog IN the park", "no
1175        // option IN any category", "every member OF the team"): conjoin
1176        // `Prep(var, obj)` so the quantifier ranges over the PP-restricted set. In
1177        // restrictor position the VP has not begun, so a preposition with an NP
1178        // object is always a restrictor modifier; a following verb/modal/copula ends
1179        // the restriction and is left untouched.
1180        while self.check_preposition() {
1181            let object_follows = matches!(
1182                self.tokens.get(self.current + 1).map(|t| &t.kind),
1183                Some(TokenType::Article(_))
1184                    | Some(TokenType::Noun(_))
1185                    | Some(TokenType::ProperName(_))
1186                    | Some(TokenType::All)
1187                    | Some(TokenType::Some)
1188                    | Some(TokenType::Any)
1189                    | Some(TokenType::Cardinal(_))
1190                    | Some(TokenType::Number(_))
1191            );
1192            if !object_follows {
1193                break;
1194            }
1195            let prep_token = self.advance().clone();
1196            let prep_name = if let TokenType::Preposition(sym) = prep_token.kind {
1197                sym
1198            } else {
1199                self.current -= 1;
1200                break;
1201            };
1202            // Skip a leading quantifier determiner in the PP object ("in ANY
1203            // category", "in EACH group") — the restrictor PP names the sort, and
1204            // `parse_noun_phrase` does not consume a bare quantifier determiner.
1205            if (self.peek().kind.is_generalized_quantifier()
1206                || matches!(
1207                    self.peek().kind,
1208                    TokenType::Any | TokenType::All | TokenType::Some | TokenType::No
1209                ))
1210                && matches!(
1211                    self.tokens.get(self.current + 1).map(|t| &t.kind),
1212                    Some(TokenType::Noun(_)) | Some(TokenType::Adjective(_))
1213                )
1214            {
1215                self.advance();
1216            }
1217            let pp_np = self.parse_noun_phrase(false)?;
1218            conditions.push(
1219                self.ctx.exprs.alloc(LogicExpr::Predicate {
1220                    name: prep_name,
1221                    args: self
1222                        .ctx
1223                        .terms
1224                        .alloc_slice([Term::Variable(var_name), Term::Constant(pp_np.noun)]),
1225                    world: None,
1226                }),
1227            );
1228        }
1229
1230        while self.check(&TokenType::That) || self.check(&TokenType::Who) {
1231            self.advance();
1232            let clause_pred = self.parse_relative_clause(var_name)?;
1233            conditions.push(clause_pred);
1234        }
1235
1236        self.combine_with_and(conditions)
1237    }
1238
1239    fn parse_verb_phrase_for_restriction(
1240        &mut self,
1241        var_name: Symbol,
1242    ) -> ParseResult<&'a LogicExpr<'a>> {
1243        let var_term = Term::Variable(var_name);
1244        let verb = self.consume_verb();
1245        let verb_str_owned = self.interner.resolve(verb).to_string();
1246
1247        // Check EARLY if verb is lexically negative (e.g., "lacks" -> "Have" with negation)
1248        // This determines whether donkey bindings need wide scope negation
1249        let (canonical_verb, is_negative) = get_canonical_verb(&verb_str_owned.to_lowercase())
1250            .map(|(lemma, neg)| (self.interner.intern(lemma), neg))
1251            .unwrap_or((verb, false));
1252
1253        // Determine if this binding needs wide scope negation wrapping
1254        let needs_wide_scope = is_negative && self.negative_scope_mode == NegativeScopeMode::Wide;
1255
1256        if Lexer::is_raising_verb(&verb_str_owned) && self.check_to() {
1257            self.advance();
1258            if self.check_verb() {
1259                let inf_verb = self.consume_verb();
1260                let inf_verb_str = self.interner.resolve(inf_verb).to_lowercase();
1261
1262                if inf_verb_str == "be" && self.check_content_word() {
1263                    let adj = self.consume_content_word()?;
1264                    let embedded = self.ctx.exprs.alloc(LogicExpr::Predicate {
1265                        name: adj,
1266                        args: self.ctx.terms.alloc_slice([Term::Variable(var_name)]),
1267                        world: None,
1268                    });
1269                    return Ok(self.ctx.exprs.alloc(LogicExpr::Scopal {
1270                        operator: verb,
1271                        body: embedded,
1272                    }));
1273                }
1274
1275                let embedded = self.ctx.exprs.alloc(LogicExpr::Predicate {
1276                    name: inf_verb,
1277                    args: self.ctx.terms.alloc_slice([Term::Variable(var_name)]),
1278                    world: None,
1279                });
1280                return Ok(self.ctx.exprs.alloc(LogicExpr::Scopal {
1281                    operator: verb,
1282                    body: embedded,
1283                }));
1284            } else if self.check(&TokenType::Is) || self.check(&TokenType::Are) {
1285                self.advance();
1286                if self.check_content_word() {
1287                    let adj = self.consume_content_word()?;
1288                    let embedded = self.ctx.exprs.alloc(LogicExpr::Predicate {
1289                        name: adj,
1290                        args: self.ctx.terms.alloc_slice([Term::Variable(var_name)]),
1291                        world: None,
1292                    });
1293                    return Ok(self.ctx.exprs.alloc(LogicExpr::Scopal {
1294                        operator: verb,
1295                        body: embedded,
1296                    }));
1297                }
1298            }
1299        }
1300
1301        let mut args = vec![var_term];
1302        let mut extra_conditions: Vec<&'a LogicExpr<'a>> = Vec::new();
1303        // A counting-NP object inside the relative clause ("who did 49 previous
1304        // jumps") becomes a ∃=n entity wrapping the whole restriction (see end).
1305        let mut object_cardinal: Option<(u32, crate::intern::Symbol)> = None;
1306
1307        if self.check(&TokenType::Reflexive) {
1308            self.advance();
1309            args.push(Term::Variable(var_name));
1310        } else if let Some(n) = self.counting_np_lookahead() {
1311            // "who did 49 previous jumps" — a digit-led counting NP with an
1312            // adjective (or a deverbal-noun head): bind a fresh ∃=n entity that
1313            // is the Theme, predicating the noun + adjectives + PPs of it, so the
1314            // count and modifiers survive instead of collapsing to a measure that
1315            // eats the adjective.
1316            self.advance(); // the number
1317            let obj_var = self.next_var_name();
1318            self.nominal_np_context = true;
1319            let obj_np_result = self.parse_noun_phrase(false);
1320            self.nominal_np_context = false;
1321            let obj_np = obj_np_result?;
1322            let mut obj_restr: &'a LogicExpr<'a> = self.ctx.exprs.alloc(LogicExpr::Predicate {
1323                name: obj_np.noun,
1324                args: self.ctx.terms.alloc_slice([Term::Variable(obj_var)]),
1325                world: None,
1326            });
1327            for &adj in obj_np.adjectives {
1328                let adj_pred = self.adjective_restriction(adj, obj_var, obj_np.noun);
1329                obj_restr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1330                    left: obj_restr,
1331                    op: TokenType::And,
1332                    right: adj_pred,
1333                });
1334            }
1335            for pp in obj_np.pps {
1336                let pp_sub = self.substitute_pp_placeholder(pp, obj_var);
1337                obj_restr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1338                    left: obj_restr,
1339                    op: TokenType::And,
1340                    right: pp_sub,
1341                });
1342            }
1343            extra_conditions.push(obj_restr);
1344            args.push(Term::Variable(obj_var));
1345            object_cardinal = Some((n, obj_var));
1346        } else if self.check_number() {
1347            // "N unit NOUN" is a measure-PREMODIFIED noun ("requires 190 degree
1348            // WATER") — ONE folded entity (190_degree_water), not a measure with
1349            // the head stranded. A noun/ambiguous head TWO tokens past the number
1350            // (after the unit word) signals this; parse the whole NP (nominal
1351            // context so an ambiguous head folds). A pure finite VERB at +2 is the
1352            // MATRIX verb, not a head ("scored 190 points WON", "saw 6 manatees
1353            // WON") — those stay a bare measured object.
1354            let premodified_noun = matches!(
1355                self.tokens.get(self.current + 2).map(|t| &t.kind),
1356                Some(TokenType::Noun(_)) | Some(TokenType::Ambiguous { .. })
1357            );
1358            if premodified_noun {
1359                let saved_ctx = self.nominal_np_context;
1360                self.nominal_np_context = true;
1361                let np_result = self.parse_noun_phrase(false);
1362                self.nominal_np_context = saved_ctx;
1363                let np = np_result?;
1364                args.push(Term::Constant(np.noun));
1365            } else {
1366                // Measured object inside a relative clause ("that saw 6 manatees"):
1367                // the count is the Theme so the constraint isn't dropped.
1368                let measure = self.parse_measure_phrase()?;
1369                args.push(*measure);
1370            }
1371        } else if (self.check_content_word() || self.check_article())
1372            && (!self.check_verb() || {
1373                // A verb-headed object is normally NOT an object (avoids eating a
1374                // second verb), EXCEPT a gerund-noun compound ("used BOWLING
1375                // pins") where the -ing word is a pre-nominal modifier of the
1376                // following noun, so the whole thing is the noun object.
1377                matches!(
1378                    self.peek().kind,
1379                    TokenType::Verb {
1380                        aspect: crate::lexicon::Aspect::Progressive,
1381                        ..
1382                    }
1383                ) && matches!(
1384                    self.tokens.get(self.current + 1).map(|t| &t.kind),
1385                    Some(TokenType::Noun(_))
1386                )
1387            })
1388        {
1389            if matches!(
1390                self.peek().kind,
1391                TokenType::Article(Definiteness::Indefinite)
1392            ) {
1393                // Parse the FULL object NP so a noun-noun compound folds ("a yoga
1394                // REGIMEN" → Yoga_regimen) instead of stranding the head — a single
1395                // consume_content_word() grabbed only the first word. Adjectives /
1396                // PPs are conjoined below (zero loss). NOTE: do NOT set
1397                // nominal_np_context here — in "Most farmers who own a donkey BEAT
1398                // it" the base-form NUCLEAR verb "beat" follows the object, and
1399                // nominal context would greedily fold it ("donkey_beat"), eating
1400                // the quantifier's nuclear scope. The Noun+Noun fold needs no flag.
1401                let obj_np = self.parse_noun_phrase(false)?;
1402                let noun = obj_np.noun;
1403                let donkey_var = self.next_var_name();
1404
1405                if needs_wide_scope {
1406                    // === WIDE SCOPE MODE ===
1407                    // Build ¬∃y(Key(y) ∧ ∃e(Have(e) ∧ Agent(e,x) ∧ Theme(e,y))) directly
1408                    //
1409                    // We capture the binding HERE and return the complete structure.
1410                    // DO NOT push to donkey_bindings - that would leak y to outer scope.
1411
1412                    // Build: Key(y)
1413                    let restriction_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
1414                        name: noun,
1415                        args: self.ctx.terms.alloc_slice([Term::Variable(donkey_var)]),
1416                        world: None,
1417                    });
1418
1419                    // Build: ∃e(Have(e) ∧ Agent(e,x) ∧ Theme(e,y)) using Neo-Davidsonian semantics
1420                    // IMPORTANT: Use build_verb_neo_event() for consistent Full-tier formatting
1421                    let inner_modifiers = self.collect_adverbs();
1422                    let verb_pred = self.build_verb_neo_event(
1423                        canonical_verb,
1424                        var_name,
1425                        Some(Term::Variable(donkey_var)),
1426                        inner_modifiers,
1427                    );
1428
1429                    // Build: Key(y) ∧ ∃e(Have(e) ∧ Agent(e,x) ∧ Theme(e,y))
1430                    let body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1431                        left: restriction_pred,
1432                        op: TokenType::And,
1433                        right: verb_pred,
1434                    });
1435
1436                    // Build: ∃y(Key(y) ∧ ∃e(Have(e) ∧ ...))
1437                    let existential = self.ctx.exprs.alloc(LogicExpr::Quantifier {
1438                        kind: QuantifierKind::Existential,
1439                        variable: donkey_var,
1440                        body,
1441                        island_id: self.current_island,
1442                    });
1443
1444                    // Build: ¬∃y(Key(y) ∧ ∃e(Have(e) ∧ ...))
1445                    let negated_existential = self.ctx.exprs.alloc(LogicExpr::UnaryOp {
1446                        op: TokenType::Not,
1447                        operand: existential,
1448                    });
1449
1450                    // Return the complete wide-scope structure directly
1451                    return Ok(negated_existential);
1452                }
1453
1454                // === NARROW SCOPE MODE ===
1455                // Push binding for later processing (normal donkey binding flow)
1456                self.donkey_bindings.push((noun, donkey_var, false, false));
1457
1458                let mut obj_restr: &'a LogicExpr<'a> = self.ctx.exprs.alloc(LogicExpr::Predicate {
1459                    name: noun,
1460                    args: self.ctx.terms.alloc_slice([Term::Variable(donkey_var)]),
1461                    world: None,
1462                });
1463                for &adj in obj_np.adjectives {
1464                    let adj_pred = self.adjective_restriction(adj, donkey_var, noun);
1465                    obj_restr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1466                        left: obj_restr,
1467                        op: TokenType::And,
1468                        right: adj_pred,
1469                    });
1470                }
1471                for pp in obj_np.pps {
1472                    let pp_sub = self.substitute_pp_placeholder(pp, donkey_var);
1473                    obj_restr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1474                        left: obj_restr,
1475                        op: TokenType::And,
1476                        right: pp_sub,
1477                    });
1478                }
1479                extra_conditions.push(obj_restr);
1480
1481                args.push(Term::Variable(donkey_var));
1482            } else {
1483                let object = self.parse_noun_phrase(false)?;
1484
1485                if self.check(&TokenType::That) || self.check(&TokenType::Who) {
1486                    self.advance();
1487                    let nested_var = self.next_var_name();
1488                    let nested_rel = self.parse_relative_clause(nested_var)?;
1489
1490                    extra_conditions.push(self.ctx.exprs.alloc(LogicExpr::Predicate {
1491                        name: object.noun,
1492                        args: self.ctx.terms.alloc_slice([Term::Variable(nested_var)]),
1493                        world: None,
1494                    }));
1495                    extra_conditions.push(nested_rel);
1496                    args.push(Term::Variable(nested_var));
1497                } else {
1498                    args.push(Term::Constant(object.noun));
1499                    // The object's PP modifiers ("won the prize IN CHEMISTRY") restrict
1500                    // the object; lower them over the object constant so they are not
1501                    // dropped — the main-clause VP keeps them, this relative VP must too.
1502                    for pp in object.pps {
1503                        let pp_sub = self.substitute_pp_self_term(pp, Term::Constant(object.noun));
1504                        extra_conditions.push(pp_sub);
1505                    }
1506                }
1507            }
1508        }
1509
1510        while self.check_preposition() {
1511            let prep_sym = match self.peek().kind {
1512                TokenType::Preposition(s) => Some(s),
1513                _ => None,
1514            };
1515            self.advance();
1516            // After a direct object has been taken, a trailing PP modifies the EVENT
1517            // ("won the prize IN CHEMISTRY", "graduated FROM Yale"): the object stays
1518            // the Theme and the PP becomes a separate predicate over the event var
1519            // (the same one build_verb_neo_event uses). Previously these trailing PP
1520            // objects were pushed past args[1] and silently dropped by `obj_term =
1521            // args.remove(1)`, losing both the preposition and the object — the
1522            // main-clause VP keeps them, so the relative/quantified VP must too. With
1523            // no direct object yet, the legacy measured-arg behavior is preserved.
1524            let attach_to_event = prep_sym.is_some() && args.len() > 1;
1525            if self.check(&TokenType::Reflexive) {
1526                self.advance();
1527                args.push(Term::Variable(var_name));
1528            } else if self.check_number() {
1529                // Numeric PP object in a relative clause ("that cooks at 385
1530                // degrees", "that sell for $2.50"): keep the measured amount.
1531                let measure = self.parse_measure_phrase()?;
1532                if attach_to_event {
1533                    let ev = self.get_event_var();
1534                    extra_conditions.push(self.ctx.exprs.alloc(LogicExpr::Predicate {
1535                        name: prep_sym.unwrap(),
1536                        args: self.ctx.terms.alloc_slice([Term::Variable(ev), *measure]),
1537                        world: None,
1538                    }));
1539                } else {
1540                    args.push(*measure);
1541                }
1542            } else if self.check_content_word() || self.check_article() {
1543                let object = self.parse_noun_phrase(false)?;
1544
1545                if self.check(&TokenType::That) || self.check(&TokenType::Who) {
1546                    self.advance();
1547                    let nested_var = self.next_var_name();
1548                    let nested_rel = self.parse_relative_clause(nested_var)?;
1549                    extra_conditions.push(self.ctx.exprs.alloc(LogicExpr::Predicate {
1550                        name: object.noun,
1551                        args: self.ctx.terms.alloc_slice([Term::Variable(nested_var)]),
1552                        world: None,
1553                    }));
1554                    extra_conditions.push(nested_rel);
1555                    args.push(Term::Variable(nested_var));
1556                } else if attach_to_event {
1557                    let ev = self.get_event_var();
1558                    extra_conditions.push(
1559                        self.ctx.exprs.alloc(LogicExpr::Predicate {
1560                            name: prep_sym.unwrap(),
1561                            args: self
1562                                .ctx
1563                                .terms
1564                                .alloc_slice([Term::Variable(ev), Term::Constant(object.noun)]),
1565                            world: None,
1566                        }),
1567                    );
1568                } else {
1569                    args.push(Term::Constant(object.noun));
1570                }
1571            }
1572        }
1573
1574        // Use the canonical verb determined at top of function
1575        // Extract object term from args if present (args[0] is subject, args[1] is object)
1576        let obj_term = if args.len() > 1 {
1577            Some(args.remove(1))
1578        } else {
1579            None
1580        };
1581        let final_modifiers = self.collect_adverbs();
1582        let base_pred =
1583            self.build_verb_neo_event(canonical_verb, var_name, obj_term, final_modifiers);
1584
1585        // Wrap in negation only for NARROW scope mode (de re reading)
1586        // Wide scope mode: negation handled via donkey binding flag in wrap_donkey_in_restriction
1587        // - Narrow: ∃y(Key(y) ∧ ¬Have(x,y)) - "missing ANY key"
1588        // - Wide:   ¬∃y(Key(y) ∧ Have(x,y)) - "has NO keys"
1589        let verb_pred = if is_negative && self.negative_scope_mode == NegativeScopeMode::Narrow {
1590            self.ctx.exprs.alloc(LogicExpr::UnaryOp {
1591                op: TokenType::Not,
1592                operand: base_pred,
1593            })
1594        } else {
1595            base_pred
1596        };
1597
1598        let mut restriction = if extra_conditions.is_empty() {
1599            verb_pred
1600        } else {
1601            extra_conditions.push(verb_pred);
1602            self.combine_with_and(extra_conditions)?
1603        };
1604
1605        // A trailing positional/temporal adverb inside the relative clause ("the
1606        // person who went FIRST", "the racer who finished LAST") anchors the
1607        // event's ordinal position — the same TemporalAnchor the main clause
1608        // builds. Without this it strands and the relative clause fails to close.
1609        if self.check_temporal_adverb() {
1610            if let TokenType::TemporalAdverb(anchor) = self.advance().kind.clone() {
1611                restriction = self.ctx.exprs.alloc(LogicExpr::TemporalAnchor {
1612                    anchor,
1613                    body: restriction,
1614                });
1615            }
1616        }
1617
1618        // A counting-NP object binds the relative-clause body as ∃=n: "the
1619        // skydiver who did 49 previous jumps" → Skydiver(s) ∧ ∃=49 j(Jump(j) ∧
1620        // Previous(j) ∧ event(s, j)). The object quantifier scopes inside the
1621        // subject's own binding (the caller conjoins the head-noun predicate).
1622        if let Some((n, obj_var)) = object_cardinal {
1623            restriction = self.ctx.exprs.alloc(LogicExpr::Quantifier {
1624                kind: QuantifierKind::Cardinal(n),
1625                variable: obj_var,
1626                body: restriction,
1627                island_id: self.current_island,
1628            });
1629        }
1630
1631        Ok(restriction)
1632    }
1633
1634    fn combine_with_and(
1635        &self,
1636        mut exprs: Vec<&'a LogicExpr<'a>>,
1637    ) -> ParseResult<&'a LogicExpr<'a>> {
1638        if exprs.is_empty() {
1639            return Err(ParseError {
1640                kind: ParseErrorKind::EmptyRestriction,
1641                span: self.current_span(),
1642            });
1643        }
1644        if exprs.len() == 1 {
1645            return Ok(exprs.remove(0));
1646        }
1647        let mut root = exprs.remove(0);
1648        for expr in exprs {
1649            root = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1650                left: root,
1651                op: TokenType::And,
1652                right: expr,
1653            });
1654        }
1655        Ok(root)
1656    }
1657
1658    fn wrap_with_definiteness_full(
1659        &mut self,
1660        np: &NounPhrase<'a>,
1661        predicate: &'a LogicExpr<'a>,
1662    ) -> ParseResult<&'a LogicExpr<'a>> {
1663        let result = self.wrap_with_definiteness_and_adjectives_and_pps(
1664            np.definiteness,
1665            np.noun,
1666            np.adjectives,
1667            np.pps,
1668            predicate,
1669        )?;
1670
1671        // If NP has a superlative, add the superlative constraint
1672        let result = if let Some(adj) = np.superlative {
1673            let superlative_expr = self.ctx.exprs.alloc(LogicExpr::Superlative {
1674                adjective: adj,
1675                subject: self.ctx.terms.alloc(Term::Constant(np.noun)),
1676                domain: np.noun,
1677            });
1678            self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1679                left: result,
1680                op: TokenType::And,
1681                right: superlative_expr,
1682            })
1683        } else {
1684            result
1685        };
1686
1687        // A possessive definite carries an existence presupposition (§8.2):
1688        // "His children are happy." ≫ He has children. The presupposed
1689        // possession is a real event — the same shape "He has children."
1690        // parses to — so it is derivable, not just printable.
1691        if let Some(possessor) = np.possessor {
1692            use crate::ast::logic::NeoEventData;
1693            use crate::ast::ThematicRole;
1694            let possessed = Term::Constant(np.noun);
1695            // A DESCRIPTIVE possessor ("the Woodard family", "the red team")
1696            // carries its own restrictor; collapsing it to the bare head silently
1697            // drops the modifier ("Woodard"/"red"). `possessor_entity` lifts it to
1698            // its own existential entity carrying the full restrictor, so the
1699            // possession event's Agent is that entity, not a stripped constant:
1700            //   ∃p(Restrictor(p) ∧ ∃e(Have(e) ∧ Agent(e,p) ∧ Theme(e,possessed))).
1701            // A bare possessor ("Agnes", "His") keeps the constant-Agent form.
1702            let (agent_term, agent_restr) = self.possessor_entity(possessor);
1703            let have = self
1704                .ctx
1705                .exprs
1706                .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
1707                    event_var: self.interner.intern("e"),
1708                    verb: self.interner.intern("Have"),
1709                    roles: self.ctx.roles.alloc_slice(vec![
1710                        (ThematicRole::Agent, agent_term),
1711                        (ThematicRole::Theme, possessed),
1712                    ]),
1713                    modifiers: self.ctx.syms.alloc_slice(vec![]),
1714                    suppress_existential: false,
1715                    world: None,
1716                })));
1717            let presupposition = self.wrap_in_possessor_entity(agent_restr, have);
1718            return Ok(self.ctx.exprs.alloc(LogicExpr::Presupposition {
1719                assertion: result,
1720                presupposition,
1721            }));
1722        }
1723
1724        Ok(result)
1725    }
1726
1727    fn wrap_with_definiteness(
1728        &mut self,
1729        definiteness: Option<Definiteness>,
1730        noun: Symbol,
1731        predicate: &'a LogicExpr<'a>,
1732    ) -> ParseResult<&'a LogicExpr<'a>> {
1733        self.wrap_with_definiteness_and_adjectives_and_pps(definiteness, noun, &[], &[], predicate)
1734    }
1735
1736    fn wrap_with_definiteness_and_adjectives(
1737        &mut self,
1738        definiteness: Option<Definiteness>,
1739        noun: Symbol,
1740        adjectives: &[Symbol],
1741        predicate: &'a LogicExpr<'a>,
1742    ) -> ParseResult<&'a LogicExpr<'a>> {
1743        self.wrap_with_definiteness_and_adjectives_and_pps(
1744            definiteness,
1745            noun,
1746            adjectives,
1747            &[],
1748            predicate,
1749        )
1750    }
1751
1752    fn wrap_with_definiteness_and_adjectives_and_pps(
1753        &mut self,
1754        definiteness: Option<Definiteness>,
1755        noun: Symbol,
1756        adjectives: &[Symbol],
1757        pps: &[&'a LogicExpr<'a>],
1758        predicate: &'a LogicExpr<'a>,
1759    ) -> ParseResult<&'a LogicExpr<'a>> {
1760        // Fold in a stashed subject relative-clause restriction (expressed over
1761        // `Constant(noun)`): conjoining it onto the predicate means every
1762        // definiteness branch's constant→variable substitution re-binds it to
1763        // the same entity, so the relative clause is never silently dropped.
1764        let predicate = match self.pending_subject_restriction {
1765            Some((restr_noun, restr)) if restr_noun == noun => {
1766                self.pending_subject_restriction = None;
1767                self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1768                    left: restr,
1769                    op: TokenType::And,
1770                    right: predicate,
1771                })
1772            }
1773            _ => predicate,
1774        };
1775        match definiteness {
1776            Some(Definiteness::Indefinite) => {
1777                let var = self.next_var_name();
1778
1779                // Introduce referent into DRS for cross-sentence anaphora
1780                // If inside a "No" quantifier, mark as NegationScope (inaccessible)
1781                let gender = Self::infer_noun_gender(self.interner.resolve(noun));
1782                let number = if Self::is_plural_noun(self.interner.resolve(noun)) {
1783                    Number::Plural
1784                } else {
1785                    Number::Singular
1786                };
1787                if self.in_negative_quantifier {
1788                    self.drs.introduce_referent_with_source(
1789                        var,
1790                        noun,
1791                        gender,
1792                        number,
1793                        ReferentSource::NegationScope,
1794                    );
1795                } else {
1796                    self.drs.introduce_referent(var, noun, gender, number);
1797                }
1798
1799                let mut restriction = self.ctx.exprs.alloc(LogicExpr::Predicate {
1800                    name: noun,
1801                    args: self.ctx.terms.alloc_slice([Term::Variable(var)]),
1802                    world: None,
1803                });
1804
1805                for adj in adjectives {
1806                    let adj_pred = self.adjective_restriction(*adj, var, noun);
1807                    restriction = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1808                        left: restriction,
1809                        op: TokenType::And,
1810                        right: adj_pred,
1811                    });
1812                }
1813
1814                for pp in pps {
1815                    let substituted_pp = self.substitute_pp_placeholder(pp, var);
1816                    restriction = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1817                        left: restriction,
1818                        op: TokenType::And,
1819                        right: substituted_pp,
1820                    });
1821                }
1822
1823                let substituted = self.substitute_constant_with_var_sym(predicate, noun, var)?;
1824                let body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1825                    left: restriction,
1826                    op: TokenType::And,
1827                    right: substituted,
1828                });
1829                Ok(self.ctx.exprs.alloc(LogicExpr::Quantifier {
1830                    kind: QuantifierKind::Existential,
1831                    variable: var,
1832                    body,
1833                    island_id: self.current_island,
1834                }))
1835            }
1836            Some(Definiteness::Definite) => {
1837                let noun_str = self.interner.resolve(noun).to_string();
1838
1839                if Self::is_plural_noun(&noun_str) {
1840                    let singular = Self::singularize_noun(&noun_str);
1841                    let singular_sym = self.interner.intern(&singular);
1842                    let sigma_term = Term::Sigma(singular_sym);
1843
1844                    let mut substituted =
1845                        self.substitute_constant_with_sigma(predicate, noun, sigma_term)?;
1846
1847                    // A definite plural's adjectives and PPs restrict the σ-term
1848                    // — "The species from Australia won." keeps From(σSpecies,
1849                    // Australia) instead of dropping the origin constraint.
1850                    for adj in adjectives {
1851                        let adj_pred = self.adjective_restriction(*adj, singular_sym, noun);
1852                        let adj_on_sigma = self.substitute_constant_with_sigma(
1853                            adj_pred,
1854                            singular_sym,
1855                            sigma_term,
1856                        )?;
1857                        substituted = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1858                            left: adj_on_sigma,
1859                            op: TokenType::And,
1860                            right: substituted,
1861                        });
1862                    }
1863                    let placeholder = self.interner.intern("_PP_SELF_");
1864                    for pp in pps {
1865                        let pp_sub = match pp {
1866                            LogicExpr::Predicate { name, args, world } => {
1867                                let new_args: Vec<Term<'a>> = args
1868                                    .iter()
1869                                    .map(|a| match a {
1870                                        Term::Variable(v) if *v == placeholder => sigma_term,
1871                                        other => *other,
1872                                    })
1873                                    .collect();
1874                                self.ctx.exprs.alloc(LogicExpr::Predicate {
1875                                    name: *name,
1876                                    args: self.ctx.terms.alloc_slice(new_args),
1877                                    world: *world,
1878                                })
1879                            }
1880                            other => *other,
1881                        };
1882                        substituted = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1883                            left: substituted,
1884                            op: TokenType::And,
1885                            right: pp_sub,
1886                        });
1887                    }
1888
1889                    let verb_name = self.find_main_verb_name(predicate);
1890                    let is_collective = verb_name
1891                        .map(|v| {
1892                            let lemma = self.interner.resolve(v);
1893                            Lexer::is_collective_verb(lemma)
1894                                // A mixed verb ("lift", "carry") defaults to
1895                                // the COLLECTIVE reading for a plural definite
1896                                // ("the boys lifted the piano" — together);
1897                                // a floated "all/each" forces distribution.
1898                                || (Lexer::is_mixed_verb(lemma) && !self.distributive_marker)
1899                        })
1900                        .unwrap_or(false);
1901
1902                    // Introduce definite plural referent to DRS for cross-sentence pronoun resolution
1903                    // E.g., "The dogs ran. They barked." - "they" refers to "dogs"
1904                    // Definite descriptions presuppose existence, so they should be globally accessible.
1905                    let gender = Gender::Unknown; // Plural entities have unknown gender
1906                    self.drs.introduce_referent_with_source(
1907                        singular_sym,
1908                        singular_sym,
1909                        gender,
1910                        Number::Plural,
1911                        ReferentSource::MainClause,
1912                    );
1913
1914                    if is_collective {
1915                        Ok(substituted)
1916                    } else {
1917                        Ok(self.ctx.exprs.alloc(LogicExpr::Distributive {
1918                            predicate: substituted,
1919                        }))
1920                    }
1921                } else {
1922                    // Van der Sandt: a definite BINDS to an accessible
1923                    // antecedent before accommodating — a re-mentioned "the
1924                    // kettle" reuses the referent instead of asserting a
1925                    // second Russell expansion (existence + uniqueness).
1926                    if adjectives.is_empty() && pps.is_empty() {
1927                        if let Some(prior) = self
1928                            .drs
1929                            .resolve_definite(self.drs.current_box_index(), noun)
1930                        {
1931                            if prior == noun {
1932                                return Ok(predicate);
1933                            }
1934                            return self.substitute_constant_with_var_sym(predicate, noun, prior);
1935                        }
1936                    }
1937
1938                    // Context-driven coreference for a MODIFIED definite whose
1939                    // head noun did not already resolve: "the hunting trip"
1940                    // binds to a prior "the hunting vacation" because the
1941                    // distinguishing modifier (Hunt) matches and trip/vacation
1942                    // are sort-compatible occasions. The modifier does the
1943                    // referring; the head noun is a soft type. No synonymy
1944                    // axiom is asserted — the later description simply reuses
1945                    // the earlier referent's variable.
1946                    if !adjectives.is_empty() && pps.is_empty() {
1947                        if let Some(prior) = self.drs.resolve_definite_by_modifier(
1948                            self.interner,
1949                            self.drs.current_box_index(),
1950                            noun,
1951                            adjectives,
1952                        ) {
1953                            return self.substitute_constant_with_var_sym(predicate, noun, prior);
1954                        }
1955                    }
1956
1957                    // In DISCOURSE mode an unbound, non-bridging definite is
1958                    // SKOLEMIZED: Russell's uniqueness licenses a witness
1959                    // constant, so cross-sentence mentions stay rigidly
1960                    // linked — `Barber(B) ∧ ∀y(Barber(y) → y = B) ∧ P(B)`
1961                    // (the very form the proof engine's definite-description
1962                    // machinery expects) — never an ∃ whose bound variable
1963                    // later premises cannot reach.
1964                    if self.world_state.in_discourse_mode()
1965                        && adjectives.is_empty()
1966                        && pps.is_empty()
1967                        && self.drs.resolve_bridging(self.interner, noun).is_none()
1968                    {
1969                        let y = self.next_var_name();
1970                        let gender = Self::infer_noun_gender(self.interner.resolve(noun));
1971                        let number = if Self::is_plural_noun(self.interner.resolve(noun)) {
1972                            Number::Plural
1973                        } else {
1974                            Number::Singular
1975                        };
1976                        // Rigid (skolem) referent: later definites and
1977                        // pronouns resolve to the constant itself.
1978                        self.drs.introduce_referent_with_source(
1979                            noun,
1980                            noun,
1981                            gender,
1982                            number,
1983                            ReferentSource::ProperName,
1984                        );
1985                        let restriction = self.ctx.exprs.alloc(LogicExpr::Predicate {
1986                            name: noun,
1987                            args: self.ctx.terms.alloc_slice([Term::Constant(noun)]),
1988                            world: None,
1989                        });
1990                        let y_restriction = self.ctx.exprs.alloc(LogicExpr::Predicate {
1991                            name: noun,
1992                            args: self.ctx.terms.alloc_slice([Term::Variable(y)]),
1993                            world: None,
1994                        });
1995                        let identity = self.ctx.exprs.alloc(LogicExpr::Identity {
1996                            left: self.ctx.terms.alloc(Term::Variable(y)),
1997                            right: self.ctx.terms.alloc(Term::Constant(noun)),
1998                        });
1999                        let uniqueness = self.ctx.exprs.alloc(LogicExpr::Quantifier {
2000                            kind: QuantifierKind::Universal,
2001                            variable: y,
2002                            body: self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2003                                left: y_restriction,
2004                                op: TokenType::Implies,
2005                                right: identity,
2006                            }),
2007                            island_id: self.current_island,
2008                        });
2009                        let described = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2010                            left: restriction,
2011                            op: TokenType::And,
2012                            right: uniqueness,
2013                        });
2014                        return Ok(self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2015                            left: described,
2016                            op: TokenType::And,
2017                            right: predicate,
2018                        }));
2019                    }
2020
2021                    let x = self.next_var_name();
2022                    let y = self.next_var_name();
2023
2024                    let mut restriction = self.ctx.exprs.alloc(LogicExpr::Predicate {
2025                        name: noun,
2026                        args: self.ctx.terms.alloc_slice([Term::Variable(x)]),
2027                        world: None,
2028                    });
2029
2030                    for adj in adjectives {
2031                        let adj_pred = self.adjective_restriction(*adj, x, noun);
2032                        restriction = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2033                            left: restriction,
2034                            op: TokenType::And,
2035                            right: adj_pred,
2036                        });
2037                    }
2038
2039                    for pp in pps {
2040                        let substituted_pp = self.substitute_pp_placeholder(pp, x);
2041                        restriction = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2042                            left: restriction,
2043                            op: TokenType::And,
2044                            right: substituted_pp,
2045                        });
2046                    }
2047
2048                    // Bridging anaphora: check if this noun is a part of a previously mentioned whole
2049                    // E.g., "I bought a car. The engine smoked." - engine is part of car
2050                    let has_prior_antecedent = self
2051                        .drs
2052                        .resolve_definite(self.drs.current_box_index(), noun)
2053                        .is_some();
2054
2055                    if !has_prior_antecedent {
2056                        if let Some((whole_var, _whole_name)) =
2057                            self.drs.resolve_bridging(self.interner, noun)
2058                        {
2059                            let part_of_sym = self.interner.intern("PartOf");
2060                            let part_of_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
2061                                name: part_of_sym,
2062                                args: self
2063                                    .ctx
2064                                    .terms
2065                                    .alloc_slice([Term::Variable(x), Term::Constant(whole_var)]),
2066                                world: None,
2067                            });
2068                            restriction = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2069                                left: restriction,
2070                                op: TokenType::And,
2071                                right: part_of_pred,
2072                            });
2073                        }
2074                    }
2075
2076                    // Introduce definite referent to DRS for cross-sentence pronoun resolution
2077                    // E.g., "The engine smoked. It broke." - "it" refers to "engine"
2078                    // Definite descriptions presuppose existence, so they should be globally
2079                    // accessible even when introduced inside conditional antecedents.
2080                    let gender = Self::infer_noun_gender(self.interner.resolve(noun));
2081                    let number = if Self::is_plural_noun(self.interner.resolve(noun)) {
2082                        Number::Plural
2083                    } else {
2084                        Number::Singular
2085                    };
2086                    // Carry the distinguishing modifier(s) so a later definite
2087                    // ("the hunting trip") can corefer to this one ("the
2088                    // hunting vacation") through a shared modifier + compatible
2089                    // occasion sort.
2090                    self.drs.introduce_referent_with_modifiers(
2091                        x,
2092                        noun,
2093                        gender,
2094                        number,
2095                        ReferentSource::MainClause,
2096                        adjectives.to_vec(),
2097                    );
2098
2099                    let mut y_restriction = self.ctx.exprs.alloc(LogicExpr::Predicate {
2100                        name: noun,
2101                        args: self.ctx.terms.alloc_slice([Term::Variable(y)]),
2102                        world: None,
2103                    });
2104                    for adj in adjectives {
2105                        let adj_pred = self.adjective_restriction(*adj, y, noun);
2106                        y_restriction = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2107                            left: y_restriction,
2108                            op: TokenType::And,
2109                            right: adj_pred,
2110                        });
2111                    }
2112
2113                    for pp in pps {
2114                        let substituted_pp = self.substitute_pp_placeholder(pp, y);
2115                        y_restriction = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2116                            left: y_restriction,
2117                            op: TokenType::And,
2118                            right: substituted_pp,
2119                        });
2120                    }
2121
2122                    let identity = self.ctx.exprs.alloc(LogicExpr::Identity {
2123                        left: self.ctx.terms.alloc(Term::Variable(y)),
2124                        right: self.ctx.terms.alloc(Term::Variable(x)),
2125                    });
2126                    let uniqueness_body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2127                        left: y_restriction,
2128                        op: TokenType::Implies,
2129                        right: identity,
2130                    });
2131                    let uniqueness = self.ctx.exprs.alloc(LogicExpr::Quantifier {
2132                        kind: QuantifierKind::Universal,
2133                        variable: y,
2134                        body: uniqueness_body,
2135                        island_id: self.current_island,
2136                    });
2137
2138                    let main_pred = self.substitute_constant_with_var_sym(predicate, noun, x)?;
2139
2140                    let inner = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2141                        left: restriction,
2142                        op: TokenType::And,
2143                        right: uniqueness,
2144                    });
2145                    let body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2146                        left: inner,
2147                        op: TokenType::And,
2148                        right: main_pred,
2149                    });
2150
2151                    Ok(self.ctx.exprs.alloc(LogicExpr::Quantifier {
2152                        kind: QuantifierKind::Existential,
2153                        variable: x,
2154                        body,
2155                        island_id: self.current_island,
2156                    }))
2157                }
2158            }
2159            Some(Definiteness::Proximal) | Some(Definiteness::Distal) => {
2160                let var = self.next_var_name();
2161
2162                let mut restriction = self.ctx.exprs.alloc(LogicExpr::Predicate {
2163                    name: noun,
2164                    args: self.ctx.terms.alloc_slice([Term::Variable(var)]),
2165                    world: None,
2166                });
2167
2168                let deictic_name = if matches!(definiteness, Some(Definiteness::Proximal)) {
2169                    self.interner.intern("Proximal")
2170                } else {
2171                    self.interner.intern("Distal")
2172                };
2173                let deictic_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
2174                    name: deictic_name,
2175                    args: self.ctx.terms.alloc_slice([Term::Variable(var)]),
2176                    world: None,
2177                });
2178                restriction = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2179                    left: restriction,
2180                    op: TokenType::And,
2181                    right: deictic_pred,
2182                });
2183
2184                for adj in adjectives {
2185                    let adj_pred = self.adjective_restriction(*adj, var, noun);
2186                    restriction = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2187                        left: restriction,
2188                        op: TokenType::And,
2189                        right: adj_pred,
2190                    });
2191                }
2192
2193                for pp in pps {
2194                    let substituted_pp = self.substitute_pp_placeholder(pp, var);
2195                    restriction = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2196                        left: restriction,
2197                        op: TokenType::And,
2198                        right: substituted_pp,
2199                    });
2200                }
2201
2202                let substituted = self.substitute_constant_with_var_sym(predicate, noun, var)?;
2203                let body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2204                    left: restriction,
2205                    op: TokenType::And,
2206                    right: substituted,
2207                });
2208                Ok(self.ctx.exprs.alloc(LogicExpr::Quantifier {
2209                    kind: QuantifierKind::Existential,
2210                    variable: var,
2211                    body,
2212                    island_id: self.current_island,
2213                }))
2214            }
2215            None => Ok(predicate),
2216        }
2217    }
2218
2219    fn wrap_with_definiteness_for_object(
2220        &mut self,
2221        definiteness: Option<Definiteness>,
2222        noun: Symbol,
2223        predicate: &'a LogicExpr<'a>,
2224    ) -> ParseResult<&'a LogicExpr<'a>> {
2225        match definiteness {
2226            Some(Definiteness::Indefinite) => {
2227                let var = self.next_var_name();
2228
2229                // Introduce referent into DRS for cross-sentence anaphora, where its scope
2230                // puts it (see `IndefiniteScope`).
2231                let gender = Self::infer_noun_gender(self.interner.resolve(noun));
2232                let number = if Self::is_plural_noun(self.interner.resolve(noun)) {
2233                    Number::Plural
2234                } else {
2235                    Number::Singular
2236                };
2237                let scope = self.introduce_indefinite(var, noun, gender, number);
2238
2239                let type_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
2240                    name: noun,
2241                    args: self.ctx.terms.alloc_slice([Term::Variable(var)]),
2242                    world: None,
2243                });
2244                let substituted = self.substitute_constant_with_var(predicate, noun, var)?;
2245                let body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2246                    left: type_pred,
2247                    op: TokenType::And,
2248                    right: substituted,
2249                });
2250                if scope == IndefiniteScope::Antecedent {
2251                    return Ok(body);
2252                }
2253                Ok(self.ctx.exprs.alloc(LogicExpr::Quantifier {
2254                    kind: QuantifierKind::Existential,
2255                    variable: var,
2256                    body,
2257                    island_id: self.current_island,
2258                }))
2259            }
2260            Some(Definiteness::Definite) => {
2261                let x = self.next_var_name();
2262                let y = self.next_var_name();
2263
2264                let type_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
2265                    name: noun,
2266                    args: self.ctx.terms.alloc_slice([Term::Variable(x)]),
2267                    world: None,
2268                });
2269
2270                let identity = self.ctx.exprs.alloc(LogicExpr::Identity {
2271                    left: self.ctx.terms.alloc(Term::Variable(y)),
2272                    right: self.ctx.terms.alloc(Term::Variable(x)),
2273                });
2274                let inner_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
2275                    name: noun,
2276                    args: self.ctx.terms.alloc_slice([Term::Variable(y)]),
2277                    world: None,
2278                });
2279                let uniqueness_body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2280                    left: inner_pred,
2281                    op: TokenType::Implies,
2282                    right: identity,
2283                });
2284                let uniqueness = self.ctx.exprs.alloc(LogicExpr::Quantifier {
2285                    kind: QuantifierKind::Universal,
2286                    variable: y,
2287                    body: uniqueness_body,
2288                    island_id: self.current_island,
2289                });
2290
2291                let main_pred = self.substitute_constant_with_var(predicate, noun, x)?;
2292
2293                let type_and_unique = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2294                    left: type_pred,
2295                    op: TokenType::And,
2296                    right: uniqueness,
2297                });
2298                let body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2299                    left: type_and_unique,
2300                    op: TokenType::And,
2301                    right: main_pred,
2302                });
2303
2304                Ok(self.ctx.exprs.alloc(LogicExpr::Quantifier {
2305                    kind: QuantifierKind::Existential,
2306                    variable: x,
2307                    body,
2308                    island_id: self.current_island,
2309                }))
2310            }
2311            Some(Definiteness::Proximal) | Some(Definiteness::Distal) => {
2312                let var = self.next_var_name();
2313
2314                let mut restriction = self.ctx.exprs.alloc(LogicExpr::Predicate {
2315                    name: noun,
2316                    args: self.ctx.terms.alloc_slice([Term::Variable(var)]),
2317                    world: None,
2318                });
2319
2320                let deictic_name = if matches!(definiteness, Some(Definiteness::Proximal)) {
2321                    self.interner.intern("Proximal")
2322                } else {
2323                    self.interner.intern("Distal")
2324                };
2325                let deictic_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
2326                    name: deictic_name,
2327                    args: self.ctx.terms.alloc_slice([Term::Variable(var)]),
2328                    world: None,
2329                });
2330                restriction = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2331                    left: restriction,
2332                    op: TokenType::And,
2333                    right: deictic_pred,
2334                });
2335
2336                let substituted = self.substitute_constant_with_var(predicate, noun, var)?;
2337                let body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2338                    left: restriction,
2339                    op: TokenType::And,
2340                    right: substituted,
2341                });
2342                Ok(self.ctx.exprs.alloc(LogicExpr::Quantifier {
2343                    kind: QuantifierKind::Existential,
2344                    variable: var,
2345                    body,
2346                    island_id: self.current_island,
2347                }))
2348            }
2349            None => Ok(predicate),
2350        }
2351    }
2352
2353    fn substitute_pp_placeholder(
2354        &mut self,
2355        pp: &'a LogicExpr<'a>,
2356        var: Symbol,
2357    ) -> &'a LogicExpr<'a> {
2358        let placeholder = self.interner.intern("_PP_SELF_");
2359        match pp {
2360            LogicExpr::Predicate { name, args, .. } => {
2361                let new_args: Vec<Term<'a>> = args
2362                    .iter()
2363                    .map(|arg| match arg {
2364                        Term::Variable(v) if *v == placeholder => Term::Variable(var),
2365                        other => *other,
2366                    })
2367                    .collect();
2368                self.ctx.exprs.alloc(LogicExpr::Predicate {
2369                    name: *name,
2370                    args: self.ctx.terms.alloc_slice(new_args),
2371                    world: None,
2372                })
2373            }
2374            // Recurse through connectives / quantifiers / events so a complex
2375            // restrictor (a reduced relative built as a NeoEvent with its gap in a
2376            // thematic role, plus event complements) binds its `_PP_SELF_` gap to
2377            // the NP's variable wherever it sits.
2378            LogicExpr::BinaryOp { left, op, right } => {
2379                let l = self.substitute_pp_placeholder(left, var);
2380                let r = self.substitute_pp_placeholder(right, var);
2381                self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2382                    left: l,
2383                    op: op.clone(),
2384                    right: r,
2385                })
2386            }
2387            LogicExpr::UnaryOp { op, operand } => {
2388                let o = self.substitute_pp_placeholder(operand, var);
2389                self.ctx.exprs.alloc(LogicExpr::UnaryOp {
2390                    op: op.clone(),
2391                    operand: o,
2392                })
2393            }
2394            LogicExpr::Quantifier {
2395                kind,
2396                variable,
2397                body,
2398                island_id,
2399            } => {
2400                let b = self.substitute_pp_placeholder(body, var);
2401                self.ctx.exprs.alloc(LogicExpr::Quantifier {
2402                    kind: *kind,
2403                    variable: *variable,
2404                    body: b,
2405                    island_id: *island_id,
2406                })
2407            }
2408            LogicExpr::Temporal { operator, body } => {
2409                let b = self.substitute_pp_placeholder(body, var);
2410                self.ctx.exprs.alloc(LogicExpr::Temporal {
2411                    operator: *operator,
2412                    body: b,
2413                })
2414            }
2415            LogicExpr::NeoEvent(data) => {
2416                let new_roles: Vec<(ThematicRole, Term<'a>)> = data
2417                    .roles
2418                    .iter()
2419                    .map(|(role, term)| {
2420                        let new_term = match term {
2421                            Term::Variable(v) if *v == placeholder => Term::Variable(var),
2422                            other => *other,
2423                        };
2424                        (*role, new_term)
2425                    })
2426                    .collect();
2427                self.ctx
2428                    .exprs
2429                    .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
2430                        event_var: data.event_var,
2431                        verb: data.verb,
2432                        roles: self.ctx.roles.alloc_slice(new_roles),
2433                        modifiers: data.modifiers,
2434                        suppress_existential: data.suppress_existential,
2435                        world: data.world,
2436                    })))
2437            }
2438            _ => pp,
2439        }
2440    }
2441
2442    fn substitute_constant_with_var(
2443        &self,
2444        expr: &'a LogicExpr<'a>,
2445        constant_name: Symbol,
2446        var_name: Symbol,
2447    ) -> ParseResult<&'a LogicExpr<'a>> {
2448        match expr {
2449            LogicExpr::Predicate { name, args, .. } => {
2450                let new_args: Vec<Term<'a>> = args
2451                    .iter()
2452                    .map(|arg| match arg {
2453                        Term::Constant(c) if *c == constant_name => Term::Variable(var_name),
2454                        Term::Constant(c) => Term::Constant(*c),
2455                        Term::Variable(v) => Term::Variable(*v),
2456                        Term::Function(n, a) => Term::Function(*n, *a),
2457                        Term::Group(m) => Term::Group(*m),
2458                        Term::Possessed {
2459                            possessor,
2460                            possessed,
2461                        } => Term::Possessed {
2462                            possessor: *possessor,
2463                            possessed: *possessed,
2464                        },
2465                        Term::Sigma(p) => Term::Sigma(*p),
2466                        Term::Intension(p) => Term::Intension(*p),
2467                        Term::Kind(k) => Term::Kind(*k),
2468                        Term::Proposition(e) => Term::Proposition(*e),
2469                        Term::Value {
2470                            kind,
2471                            unit,
2472                            dimension,
2473                        } => Term::Value {
2474                            kind: *kind,
2475                            unit: *unit,
2476                            dimension: *dimension,
2477                        },
2478                    })
2479                    .collect();
2480                Ok(self.ctx.exprs.alloc(LogicExpr::Predicate {
2481                    name: *name,
2482                    args: self.ctx.terms.alloc_slice(new_args),
2483                    world: None,
2484                }))
2485            }
2486            LogicExpr::Temporal { operator, body } => {
2487                Ok(self.ctx.exprs.alloc(LogicExpr::Temporal {
2488                    operator: *operator,
2489                    body: self.substitute_constant_with_var(body, constant_name, var_name)?,
2490                }))
2491            }
2492            LogicExpr::Aspectual { operator, body } => {
2493                Ok(self.ctx.exprs.alloc(LogicExpr::Aspectual {
2494                    operator: *operator,
2495                    body: self.substitute_constant_with_var(body, constant_name, var_name)?,
2496                }))
2497            }
2498            LogicExpr::UnaryOp { op, operand } => Ok(self.ctx.exprs.alloc(LogicExpr::UnaryOp {
2499                op: op.clone(),
2500                operand: self.substitute_constant_with_var(operand, constant_name, var_name)?,
2501            })),
2502            LogicExpr::BinaryOp { left, op, right } => {
2503                Ok(self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2504                    left: self.substitute_constant_with_var(left, constant_name, var_name)?,
2505                    op: op.clone(),
2506                    right: self.substitute_constant_with_var(right, constant_name, var_name)?,
2507                }))
2508            }
2509            LogicExpr::Event { predicate, adverbs } => Ok(self.ctx.exprs.alloc(LogicExpr::Event {
2510                predicate: self.substitute_constant_with_var(predicate, constant_name, var_name)?,
2511                adverbs: *adverbs,
2512            })),
2513            LogicExpr::TemporalAnchor { anchor, body } => {
2514                Ok(self.ctx.exprs.alloc(LogicExpr::TemporalAnchor {
2515                    anchor: *anchor,
2516                    body: self.substitute_constant_with_var(body, constant_name, var_name)?,
2517                }))
2518            }
2519            LogicExpr::NeoEvent(data) => {
2520                // Substitute constants in thematic roles (Agent, Theme, etc.)
2521                let new_roles: Vec<(crate::ast::ThematicRole, Term<'a>)> = data
2522                    .roles
2523                    .iter()
2524                    .map(|(role, term)| {
2525                        let new_term = match term {
2526                            Term::Constant(c) if *c == constant_name => Term::Variable(var_name),
2527                            Term::Constant(c) => Term::Constant(*c),
2528                            Term::Variable(v) => Term::Variable(*v),
2529                            Term::Function(n, a) => Term::Function(*n, *a),
2530                            Term::Group(m) => Term::Group(*m),
2531                            Term::Possessed {
2532                                possessor,
2533                                possessed,
2534                            } => Term::Possessed {
2535                                possessor: *possessor,
2536                                possessed: *possessed,
2537                            },
2538                            Term::Sigma(p) => Term::Sigma(*p),
2539                            Term::Intension(p) => Term::Intension(*p),
2540                            Term::Kind(k) => Term::Kind(*k),
2541                            Term::Proposition(e) => Term::Proposition(*e),
2542                            Term::Value {
2543                                kind,
2544                                unit,
2545                                dimension,
2546                            } => Term::Value {
2547                                kind: *kind,
2548                                unit: *unit,
2549                                dimension: *dimension,
2550                            },
2551                        };
2552                        (*role, new_term)
2553                    })
2554                    .collect();
2555                Ok(self
2556                    .ctx
2557                    .exprs
2558                    .alloc(LogicExpr::NeoEvent(Box::new(crate::ast::NeoEventData {
2559                        event_var: data.event_var,
2560                        verb: data.verb,
2561                        roles: self.ctx.roles.alloc_slice(new_roles),
2562                        modifiers: data.modifiers,
2563                        suppress_existential: data.suppress_existential,
2564                        world: None,
2565                    }))))
2566            }
2567            // Recurse into nested quantifiers to substitute constants in their bodies
2568            LogicExpr::Quantifier {
2569                kind,
2570                variable,
2571                body,
2572                island_id,
2573            } => {
2574                let new_body = self.substitute_constant_with_var(body, constant_name, var_name)?;
2575                Ok(self.ctx.exprs.alloc(LogicExpr::Quantifier {
2576                    kind: *kind,
2577                    variable: *variable,
2578                    body: new_body,
2579                    island_id: *island_id,
2580                }))
2581            }
2582            LogicExpr::Control {
2583                verb,
2584                subject,
2585                object,
2586                infinitive,
2587            } => {
2588                let sub_term = |t: &Term<'a>| -> Term<'a> {
2589                    match t {
2590                        Term::Constant(c) if *c == constant_name => Term::Variable(var_name),
2591                        other => other.clone(),
2592                    }
2593                };
2594                Ok(self.ctx.exprs.alloc(LogicExpr::Control {
2595                    verb: *verb,
2596                    subject: self.ctx.terms.alloc(sub_term(subject)),
2597                    object: match object {
2598                        Some(o) => Some(&*self.ctx.terms.alloc(sub_term(o))),
2599                        None => None,
2600                    },
2601                    infinitive: self.substitute_constant_with_var(
2602                        infinitive,
2603                        constant_name,
2604                        var_name,
2605                    )?,
2606                }))
2607            }
2608            _ => Ok(expr),
2609        }
2610    }
2611
2612    fn substitute_constant_with_var_sym(
2613        &self,
2614        expr: &'a LogicExpr<'a>,
2615        constant_name: Symbol,
2616        var_name: Symbol,
2617    ) -> ParseResult<&'a LogicExpr<'a>> {
2618        self.substitute_constant_with_var(expr, constant_name, var_name)
2619    }
2620
2621    fn substitute_variable_with_constant(
2622        &self,
2623        expr: &'a LogicExpr<'a>,
2624        from_var: Symbol,
2625        to_const: Symbol,
2626    ) -> ParseResult<&'a LogicExpr<'a>> {
2627        let map_term = |t: &Term<'a>| -> Term<'a> {
2628            match t {
2629                Term::Variable(v) if *v == from_var => Term::Constant(to_const),
2630                other => other.clone(),
2631            }
2632        };
2633        match expr {
2634            LogicExpr::Predicate { name, args, world } => {
2635                let new_args: Vec<Term<'a>> = args.iter().map(&map_term).collect();
2636                Ok(self.ctx.exprs.alloc(LogicExpr::Predicate {
2637                    name: *name,
2638                    args: self.ctx.terms.alloc_slice(new_args),
2639                    world: *world,
2640                }))
2641            }
2642            LogicExpr::Identity { left, right } => Ok(self.ctx.exprs.alloc(LogicExpr::Identity {
2643                left: self.ctx.terms.alloc(map_term(left)),
2644                right: self.ctx.terms.alloc(map_term(right)),
2645            })),
2646            LogicExpr::Temporal { operator, body } => {
2647                Ok(self.ctx.exprs.alloc(LogicExpr::Temporal {
2648                    operator: *operator,
2649                    body: self.substitute_variable_with_constant(body, from_var, to_const)?,
2650                }))
2651            }
2652            LogicExpr::Aspectual { operator, body } => {
2653                Ok(self.ctx.exprs.alloc(LogicExpr::Aspectual {
2654                    operator: *operator,
2655                    body: self.substitute_variable_with_constant(body, from_var, to_const)?,
2656                }))
2657            }
2658            LogicExpr::UnaryOp { op, operand } => Ok(self.ctx.exprs.alloc(LogicExpr::UnaryOp {
2659                op: op.clone(),
2660                operand: self.substitute_variable_with_constant(operand, from_var, to_const)?,
2661            })),
2662            LogicExpr::BinaryOp { left, op, right } => {
2663                Ok(self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2664                    left: self.substitute_variable_with_constant(left, from_var, to_const)?,
2665                    op: op.clone(),
2666                    right: self.substitute_variable_with_constant(right, from_var, to_const)?,
2667                }))
2668            }
2669            LogicExpr::Event { predicate, adverbs } => Ok(self.ctx.exprs.alloc(LogicExpr::Event {
2670                predicate: self.substitute_variable_with_constant(predicate, from_var, to_const)?,
2671                adverbs: *adverbs,
2672            })),
2673            LogicExpr::TemporalAnchor { anchor, body } => {
2674                Ok(self.ctx.exprs.alloc(LogicExpr::TemporalAnchor {
2675                    anchor: *anchor,
2676                    body: self.substitute_variable_with_constant(body, from_var, to_const)?,
2677                }))
2678            }
2679            LogicExpr::NeoEvent(data) => {
2680                let new_roles: Vec<(crate::ast::ThematicRole, Term<'a>)> = data
2681                    .roles
2682                    .iter()
2683                    .map(|(role, term)| (*role, map_term(term)))
2684                    .collect();
2685                Ok(self
2686                    .ctx
2687                    .exprs
2688                    .alloc(LogicExpr::NeoEvent(Box::new(crate::ast::NeoEventData {
2689                        event_var: data.event_var,
2690                        verb: data.verb,
2691                        roles: self.ctx.roles.alloc_slice(new_roles),
2692                        modifiers: data.modifiers,
2693                        suppress_existential: data.suppress_existential,
2694                        world: None,
2695                    }))))
2696            }
2697            LogicExpr::Quantifier {
2698                kind,
2699                variable,
2700                body,
2701                island_id,
2702            } => {
2703                // A nested quantifier that re-binds `from_var` shadows the gap;
2704                // leave its body untouched in that case.
2705                if *variable == from_var {
2706                    return Ok(expr);
2707                }
2708                Ok(self.ctx.exprs.alloc(LogicExpr::Quantifier {
2709                    kind: *kind,
2710                    variable: *variable,
2711                    body: self.substitute_variable_with_constant(body, from_var, to_const)?,
2712                    island_id: *island_id,
2713                }))
2714            }
2715            LogicExpr::Control {
2716                verb,
2717                subject,
2718                object,
2719                infinitive,
2720            } => Ok(self.ctx.exprs.alloc(LogicExpr::Control {
2721                verb: *verb,
2722                subject: self.ctx.terms.alloc(map_term(subject)),
2723                object: object.map(|o| &*self.ctx.terms.alloc(map_term(o))),
2724                infinitive: self
2725                    .substitute_variable_with_constant(infinitive, from_var, to_const)?,
2726            })),
2727            _ => Ok(expr),
2728        }
2729    }
2730
2731    fn substitute_constant_with_sigma(
2732        &self,
2733        expr: &'a LogicExpr<'a>,
2734        constant_name: Symbol,
2735        sigma_term: Term<'a>,
2736    ) -> ParseResult<&'a LogicExpr<'a>> {
2737        match expr {
2738            LogicExpr::Predicate { name, args, .. } => {
2739                let new_args: Vec<Term<'a>> = args
2740                    .iter()
2741                    .map(|arg| match arg {
2742                        Term::Constant(c) if *c == constant_name => sigma_term.clone(),
2743                        Term::Constant(c) => Term::Constant(*c),
2744                        Term::Variable(v) => Term::Variable(*v),
2745                        Term::Function(n, a) => Term::Function(*n, *a),
2746                        Term::Group(m) => Term::Group(*m),
2747                        Term::Possessed {
2748                            possessor,
2749                            possessed,
2750                        } => Term::Possessed {
2751                            possessor: *possessor,
2752                            possessed: *possessed,
2753                        },
2754                        Term::Sigma(p) => Term::Sigma(*p),
2755                        Term::Intension(p) => Term::Intension(*p),
2756                        Term::Kind(k) => Term::Kind(*k),
2757                        Term::Proposition(e) => Term::Proposition(*e),
2758                        Term::Value {
2759                            kind,
2760                            unit,
2761                            dimension,
2762                        } => Term::Value {
2763                            kind: *kind,
2764                            unit: *unit,
2765                            dimension: *dimension,
2766                        },
2767                    })
2768                    .collect();
2769                Ok(self.ctx.exprs.alloc(LogicExpr::Predicate {
2770                    name: *name,
2771                    args: self.ctx.terms.alloc_slice(new_args),
2772                    world: None,
2773                }))
2774            }
2775            LogicExpr::Temporal { operator, body } => {
2776                Ok(self.ctx.exprs.alloc(LogicExpr::Temporal {
2777                    operator: *operator,
2778                    body: self.substitute_constant_with_sigma(body, constant_name, sigma_term)?,
2779                }))
2780            }
2781            LogicExpr::Aspectual { operator, body } => {
2782                Ok(self.ctx.exprs.alloc(LogicExpr::Aspectual {
2783                    operator: *operator,
2784                    body: self.substitute_constant_with_sigma(body, constant_name, sigma_term)?,
2785                }))
2786            }
2787            LogicExpr::UnaryOp { op, operand } => Ok(self.ctx.exprs.alloc(LogicExpr::UnaryOp {
2788                op: op.clone(),
2789                operand: self.substitute_constant_with_sigma(operand, constant_name, sigma_term)?,
2790            })),
2791            LogicExpr::BinaryOp { left, op, right } => {
2792                Ok(self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2793                    left: self.substitute_constant_with_sigma(
2794                        left,
2795                        constant_name,
2796                        sigma_term.clone(),
2797                    )?,
2798                    op: op.clone(),
2799                    right: self.substitute_constant_with_sigma(right, constant_name, sigma_term)?,
2800                }))
2801            }
2802            LogicExpr::Event { predicate, adverbs } => Ok(self.ctx.exprs.alloc(LogicExpr::Event {
2803                predicate: self.substitute_constant_with_sigma(
2804                    predicate,
2805                    constant_name,
2806                    sigma_term,
2807                )?,
2808                adverbs: *adverbs,
2809            })),
2810            LogicExpr::TemporalAnchor { anchor, body } => {
2811                Ok(self.ctx.exprs.alloc(LogicExpr::TemporalAnchor {
2812                    anchor: *anchor,
2813                    body: self.substitute_constant_with_sigma(body, constant_name, sigma_term)?,
2814                }))
2815            }
2816            LogicExpr::NeoEvent(data) => {
2817                let new_roles: Vec<(crate::ast::ThematicRole, Term<'a>)> = data
2818                    .roles
2819                    .iter()
2820                    .map(|(role, term)| {
2821                        let new_term = match term {
2822                            Term::Constant(c) if *c == constant_name => sigma_term.clone(),
2823                            Term::Constant(c) => Term::Constant(*c),
2824                            Term::Variable(v) => Term::Variable(*v),
2825                            Term::Function(n, a) => Term::Function(*n, *a),
2826                            Term::Group(m) => Term::Group(*m),
2827                            Term::Possessed {
2828                                possessor,
2829                                possessed,
2830                            } => Term::Possessed {
2831                                possessor: *possessor,
2832                                possessed: *possessed,
2833                            },
2834                            Term::Sigma(p) => Term::Sigma(*p),
2835                            Term::Intension(p) => Term::Intension(*p),
2836                            Term::Kind(k) => Term::Kind(*k),
2837                            Term::Proposition(e) => Term::Proposition(*e),
2838                            Term::Value {
2839                                kind,
2840                                unit,
2841                                dimension,
2842                            } => Term::Value {
2843                                kind: *kind,
2844                                unit: *unit,
2845                                dimension: *dimension,
2846                            },
2847                        };
2848                        (*role, new_term)
2849                    })
2850                    .collect();
2851                Ok(self
2852                    .ctx
2853                    .exprs
2854                    .alloc(LogicExpr::NeoEvent(Box::new(crate::ast::NeoEventData {
2855                        event_var: data.event_var,
2856                        verb: data.verb,
2857                        roles: self.ctx.roles.alloc_slice(new_roles),
2858                        modifiers: data.modifiers,
2859                        suppress_existential: data.suppress_existential,
2860                        world: None,
2861                    }))))
2862            }
2863            LogicExpr::Distributive { predicate } => {
2864                Ok(self.ctx.exprs.alloc(LogicExpr::Distributive {
2865                    predicate: self.substitute_constant_with_sigma(
2866                        predicate,
2867                        constant_name,
2868                        sigma_term,
2869                    )?,
2870                }))
2871            }
2872            _ => Ok(expr),
2873        }
2874    }
2875
2876    fn find_main_verb_name(&self, expr: &LogicExpr<'a>) -> Option<Symbol> {
2877        match expr {
2878            LogicExpr::Predicate { name, .. } => Some(*name),
2879            LogicExpr::NeoEvent(data) => Some(data.verb),
2880            LogicExpr::Temporal { body, .. } => self.find_main_verb_name(body),
2881            LogicExpr::Aspectual { body, .. } => self.find_main_verb_name(body),
2882            LogicExpr::Event { predicate, .. } => self.find_main_verb_name(predicate),
2883            LogicExpr::TemporalAnchor { body, .. } => self.find_main_verb_name(body),
2884            LogicExpr::UnaryOp { operand, .. } => self.find_main_verb_name(operand),
2885            LogicExpr::BinaryOp { left, .. } => self.find_main_verb_name(left),
2886            _ => None,
2887        }
2888    }
2889
2890    fn transform_cardinal_to_group(
2891        &mut self,
2892        expr: &'a LogicExpr<'a>,
2893    ) -> ParseResult<&'a LogicExpr<'a>> {
2894        match expr {
2895            LogicExpr::Quantifier {
2896                kind: QuantifierKind::Cardinal(n),
2897                variable,
2898                body,
2899                ..
2900            } => {
2901                let group_var = self.interner.intern("g");
2902                let member_var = *variable;
2903
2904                // Extract the restriction (first conjunct) and the body (rest)
2905                // The structure is: restriction ∧ body_rest
2906                let (restriction, body_rest) = match body {
2907                    LogicExpr::BinaryOp {
2908                        left,
2909                        op: TokenType::And,
2910                        right,
2911                    } => (*left, *right),
2912                    _ => return Ok(expr),
2913                };
2914
2915                // Substitute the member variable with the group variable in the body
2916                let transformed_body =
2917                    self.substitute_constant_with_var_sym(body_rest, member_var, group_var)?;
2918
2919                Ok(self.ctx.exprs.alloc(LogicExpr::GroupQuantifier {
2920                    group_var,
2921                    count: *n,
2922                    member_var,
2923                    restriction,
2924                    body: transformed_body,
2925                }))
2926            }
2927            // Recursively transform nested expressions
2928            LogicExpr::Temporal { operator, body } => {
2929                let transformed = self.transform_cardinal_to_group(body)?;
2930                Ok(self.ctx.exprs.alloc(LogicExpr::Temporal {
2931                    operator: *operator,
2932                    body: transformed,
2933                }))
2934            }
2935            LogicExpr::Aspectual { operator, body } => {
2936                let transformed = self.transform_cardinal_to_group(body)?;
2937                Ok(self.ctx.exprs.alloc(LogicExpr::Aspectual {
2938                    operator: *operator,
2939                    body: transformed,
2940                }))
2941            }
2942            LogicExpr::UnaryOp { op, operand } => {
2943                let transformed = self.transform_cardinal_to_group(operand)?;
2944                Ok(self.ctx.exprs.alloc(LogicExpr::UnaryOp {
2945                    op: op.clone(),
2946                    operand: transformed,
2947                }))
2948            }
2949            LogicExpr::BinaryOp { left, op, right } => {
2950                let transformed_left = self.transform_cardinal_to_group(left)?;
2951                let transformed_right = self.transform_cardinal_to_group(right)?;
2952                Ok(self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2953                    left: transformed_left,
2954                    op: op.clone(),
2955                    right: transformed_right,
2956                }))
2957            }
2958            LogicExpr::Distributive { predicate } => {
2959                let transformed = self.transform_cardinal_to_group(predicate)?;
2960                Ok(self.ctx.exprs.alloc(LogicExpr::Distributive {
2961                    predicate: transformed,
2962                }))
2963            }
2964            LogicExpr::Quantifier {
2965                kind,
2966                variable,
2967                body,
2968                island_id,
2969            } => {
2970                let transformed = self.transform_cardinal_to_group(body)?;
2971                Ok(self.ctx.exprs.alloc(LogicExpr::Quantifier {
2972                    kind: kind.clone(),
2973                    variable: *variable,
2974                    body: transformed,
2975                    island_id: *island_id,
2976                }))
2977            }
2978            _ => Ok(expr),
2979        }
2980    }
2981
2982    fn build_verb_neo_event(
2983        &mut self,
2984        verb: Symbol,
2985        subject_var: Symbol,
2986        object: Option<Term<'a>>,
2987        modifiers: Vec<Symbol>,
2988    ) -> &'a LogicExpr<'a> {
2989        let event_var = self.get_event_var();
2990
2991        // Check if verb is unaccusative (intransitive subject is Theme, not Agent)
2992        let verb_str = self.interner.resolve(verb).to_lowercase();
2993        let is_unaccusative = lookup_verb_db(&verb_str)
2994            .map(|meta| meta.features.contains(&Feature::Unaccusative))
2995            .unwrap_or(false);
2996
2997        // Determine subject role: unaccusative verbs without object use Theme
2998        let has_object = object.is_some();
2999        let subject_role = if is_unaccusative && !has_object {
3000            ThematicRole::Theme
3001        } else {
3002            ThematicRole::Agent
3003        };
3004
3005        // Build roles vector
3006        let mut roles = vec![(subject_role, Term::Variable(subject_var))];
3007        if let Some(obj_term) = object {
3008            roles.push((ThematicRole::Theme, obj_term));
3009        }
3010
3011        // Create NeoEventData with suppress_existential: false
3012        // Each quantified individual gets their own event (distributive reading)
3013        self.ctx
3014            .exprs
3015            .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
3016                event_var,
3017                verb,
3018                roles: self.ctx.roles.alloc_slice(roles),
3019                modifiers: self.ctx.syms.alloc_slice(modifiers),
3020                suppress_existential: false,
3021                world: None,
3022            })))
3023    }
3024}
3025
3026// Helper methods for donkey binding scope handling
3027impl<'a, 'ctx, 'int> Parser<'a, 'ctx, 'int> {
3028    /// The quantifier `determiner` binds: `any` reads existentially under negation and universally
3029    /// elsewhere, and every other determiner binds its own ([`QuantifierKind::of_determiner`]).
3030    pub(super) fn determiner_quantifier(
3031        &self,
3032        determiner: &TokenType,
3033    ) -> ParseResult<QuantifierKind> {
3034        if matches!(determiner, TokenType::Any) {
3035            return Ok(if self.is_negative_context() {
3036                QuantifierKind::Existential
3037            } else {
3038                QuantifierKind::Universal
3039            });
3040        }
3041        QuantifierKind::of_determiner(determiner).ok_or_else(|| ParseError {
3042            kind: ParseErrorKind::UnknownQuantifier {
3043                found: determiner.clone(),
3044            },
3045            span: self.current_span(),
3046        })
3047    }
3048
3049    /// The body of `determiner`'s quantifier over `restrictor` and `scope`: `R → ¬S` under `no`,
3050    /// `R → S` under a quantifier that restricts by implication, `R ∧ S` under the rest.
3051    pub(super) fn determiner_body(
3052        &self,
3053        determiner: &TokenType,
3054        restrictor: &'a LogicExpr<'a>,
3055        scope: &'a LogicExpr<'a>,
3056    ) -> ParseResult<&'a LogicExpr<'a>> {
3057        let (op, right): (TokenType, &'a LogicExpr<'a>) = if matches!(determiner, TokenType::No) {
3058            let negated = self.ctx.exprs.alloc(LogicExpr::UnaryOp {
3059                op: TokenType::Not,
3060                operand: scope,
3061            });
3062            (TokenType::Implies, negated)
3063        } else if self
3064            .determiner_quantifier(determiner)?
3065            .restricts_by_implication()
3066        {
3067            (TokenType::Implies, scope)
3068        } else {
3069            (TokenType::And, scope)
3070        };
3071        Ok(self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3072            left: restrictor,
3073            op,
3074            right,
3075        }))
3076    }
3077
3078    /// The quantifier a determiner heading an argument other than the subject — an object, a
3079    /// recipient, a comparison's standard, a passive agent — binds over `variable`: `any` and a
3080    /// token that is no determiner read as an indefinite, `∃v(R ∧ S)`, and every other determiner
3081    /// reads as it does at the head of a subject.
3082    pub(super) fn quantify_argument(
3083        &self,
3084        determiner: &TokenType,
3085        variable: Symbol,
3086        restrictor: &'a LogicExpr<'a>,
3087        scope: &'a LogicExpr<'a>,
3088    ) -> &'a LogicExpr<'a> {
3089        let indefinite = || -> &'a LogicExpr<'a> {
3090            self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3091                left: restrictor,
3092                op: TokenType::And,
3093                right: scope,
3094            })
3095        };
3096        let (kind, body) = QuantifierKind::of_determiner(determiner)
3097            .and_then(|kind| {
3098                Some((
3099                    kind,
3100                    self.determiner_body(determiner, restrictor, scope).ok()?,
3101                ))
3102            })
3103            .unwrap_or_else(|| (QuantifierKind::Existential, indefinite()));
3104        self.ctx.exprs.alloc(LogicExpr::Quantifier {
3105            kind,
3106            variable,
3107            body,
3108            island_id: self.current_island,
3109        })
3110    }
3111
3112    /// Is the parser at a position where a finished clause may legitimately
3113    /// end? Used to detect under-consumption by specialized sub-grammars.
3114    pub(super) fn at_clause_boundary(&self) -> bool {
3115        matches!(
3116            self.peek().kind,
3117            TokenType::Period
3118                | TokenType::Exclamation
3119                | TokenType::EOF
3120                | TokenType::Comma
3121                | TokenType::InfinitelyOften
3122                | TokenType::RParen
3123                | TokenType::And
3124                | TokenType::Or
3125                | TokenType::Iff
3126                | TokenType::Then
3127        )
3128    }
3129
3130    /// Quantified clause whose VP is parsed by the FULL predicate parser with
3131    /// the subject bound to the quantified variable. The under-consumption
3132    /// fallback for frames the specialized quantified grammar does not cover
3133    /// (reflexives, reciprocals, control infinitives, ditransitives,
3134    /// comparatives, adverbs, …).
3135    fn parse_quantified_delegating(&mut self) -> ParseResult<&'a LogicExpr<'a>> {
3136        use super::verb::LogicVerbParsing;
3137
3138        let quantifier_token = self.previous().kind.clone();
3139        let var_name = self.next_var_name();
3140
3141        let was_in_negative_quantifier = self.in_negative_quantifier;
3142        if matches!(quantifier_token, TokenType::No) {
3143            self.in_negative_quantifier = true;
3144        }
3145
3146        let restriction = self.parse_restriction(var_name)?;
3147
3148        // Reciprocal VP ("helped each other"): every pair of distinct members
3149        // of the restriction stands in the relation —
3150        // ∀y((R(y) ∧ ¬(y = x)) → ∃e(V(e) ∧ Agent(e, x) ∧ Theme(e, y))).
3151        let mut copula_vp: Option<&'a LogicExpr<'a>> = None;
3152        if matches!(self.peek().kind, TokenType::Verb { .. })
3153            && matches!(
3154                self.tokens.get(self.current + 1).map(|t| t.kind.clone()),
3155                Some(TokenType::Reciprocal)
3156            )
3157        {
3158            let (verb, recip_time, _, _) = self.consume_verb_with_metadata();
3159            self.advance(); // the reciprocal
3160            let other_var = self.next_var_name();
3161            let other_restriction = self.rename_var_in_expr(restriction, var_name, other_var);
3162            let distinct = self.ctx.exprs.alloc(LogicExpr::UnaryOp {
3163                op: TokenType::Not,
3164                operand: self.ctx.exprs.alloc(LogicExpr::Identity {
3165                    left: self.ctx.terms.alloc(Term::Variable(other_var)),
3166                    right: self.ctx.terms.alloc(Term::Variable(var_name)),
3167                }),
3168            });
3169            let modifiers = match recip_time {
3170                Time::Past => vec![self.interner.intern("Past")],
3171                Time::Future => vec![self.interner.intern("Future")],
3172                _ => vec![],
3173            };
3174            let event_var = self.get_event_var();
3175            let suppress_existential = self.drs.in_conditional_antecedent();
3176            let event = self
3177                .ctx
3178                .exprs
3179                .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
3180                    event_var,
3181                    verb,
3182                    roles: self.ctx.roles.alloc_slice(vec![
3183                        (ThematicRole::Agent, Term::Variable(var_name)),
3184                        (ThematicRole::Theme, Term::Variable(other_var)),
3185                    ]),
3186                    modifiers: self.ctx.syms.alloc_slice(modifiers),
3187                    suppress_existential,
3188                    world: None,
3189                })));
3190            let antecedent = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3191                left: other_restriction,
3192                op: TokenType::And,
3193                right: distinct,
3194            });
3195            let pair_body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3196                left: antecedent,
3197                op: TokenType::Implies,
3198                right: event,
3199            });
3200            copula_vp = Some(self.ctx.exprs.alloc(LogicExpr::Quantifier {
3201                kind: QuantifierKind::Universal,
3202                variable: other_var,
3203                body: pair_body,
3204                island_id: self.current_island,
3205            }));
3206        }
3207
3208        // Copula-initial VP. A progressive participle keeps the full predicate
3209        // parser (the copula only carries tense: "were running quickly"); a
3210        // passive participle predicates the subject variable as Theme with an
3211        // optional by-phrase Agent ("were read by some students").
3212        if matches!(
3213            self.peek().kind,
3214            TokenType::Is | TokenType::Are | TokenType::Was | TokenType::Were
3215        ) {
3216            let copula_past = matches!(self.peek().kind, TokenType::Was | TokenType::Were);
3217            if let Some(TokenType::Verb { aspect, .. }) =
3218                self.tokens.get(self.current + 1).map(|t| t.kind.clone())
3219            {
3220                if aspect == crate::lexicon::Aspect::Progressive {
3221                    self.advance(); // copula carries tense only
3222                    self.pending_time = Some(if copula_past { Time::Past } else { Time::None });
3223                } else {
3224                    self.advance(); // copula
3225                    let (verb, _, _, _) = self.consume_verb_with_metadata();
3226                    let mut modifiers = if copula_past {
3227                        vec![self.interner.intern("Past")]
3228                    } else {
3229                        vec![]
3230                    };
3231                    modifiers.extend(self.collect_adverbs());
3232
3233                    let mut roles = vec![(ThematicRole::Theme, Term::Variable(var_name))];
3234                    let mut agent_quant: Option<(TokenType, Symbol, Symbol)> = None;
3235                    if self.check_preposition_is("by") {
3236                        self.advance(); // by
3237                        if self.check_quantifier() {
3238                            let q = self.advance().kind.clone();
3239                            let a_np = self.parse_noun_phrase(false)?;
3240                            let a_var = self.next_var_name();
3241                            roles.push((ThematicRole::Agent, Term::Variable(a_var)));
3242                            agent_quant = Some((q, a_var, a_np.noun));
3243                        } else if self.check_content_word() || self.check_article() {
3244                            let a_np = self.parse_noun_phrase(false)?;
3245                            roles.push((ThematicRole::Agent, Term::Constant(a_np.noun)));
3246                        }
3247                    }
3248
3249                    let event_var = self.get_event_var();
3250                    let suppress_existential = self.drs.in_conditional_antecedent();
3251                    let passive =
3252                        self.ctx
3253                            .exprs
3254                            .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
3255                                event_var,
3256                                verb,
3257                                roles: self.ctx.roles.alloc_slice(roles),
3258                                modifiers: self.ctx.syms.alloc_slice(modifiers),
3259                                suppress_existential,
3260                                world: None,
3261                            })));
3262                    copula_vp = Some(if let Some((q, a_var, a_noun)) = agent_quant {
3263                        let a_restriction = self.ctx.exprs.alloc(LogicExpr::Predicate {
3264                            name: a_noun,
3265                            args: self.ctx.terms.alloc_slice([Term::Variable(a_var)]),
3266                            world: None,
3267                        });
3268                        self.quantify_argument(&q, a_var, a_restriction, passive)
3269                    } else {
3270                        passive
3271                    });
3272                }
3273            }
3274        }
3275
3276        let vp = match copula_vp {
3277            Some(vp) => vp,
3278            None => self.parse_predicate_with_subject_as_var(var_name)?,
3279        };
3280        // Sentence-final temporal anchor ("studied yesterday") — the same
3281        // wrapping the simple-subject clause path applies.
3282        let vp = if self.check_temporal_adverb() {
3283            if let TokenType::TemporalAdverb(anchor) = self.advance().kind.clone() {
3284                &*self
3285                    .ctx
3286                    .exprs
3287                    .alloc(LogicExpr::TemporalAnchor { anchor, body: vp })
3288            } else {
3289                vp
3290            }
3291        } else {
3292            vp
3293        };
3294        self.in_negative_quantifier = was_in_negative_quantifier;
3295
3296        let kind = self.determiner_quantifier(&quantifier_token)?;
3297        let mut body = self.determiner_body(&quantifier_token, restriction, vp)?;
3298
3299        // Donkey closure: an indefinite introduced inside the restriction and
3300        // picked up by the VP ("Every man who owns a book gives it …") is a
3301        // free variable in both — close it at the quantifier (universal force
3302        // under a quantifier that restricts by implication, existential otherwise).
3303        let mut restriction_vars = Vec::new();
3304        self.collect_unbound_vars(restriction, &mut vec![var_name], &mut restriction_vars);
3305        for donkey_var in restriction_vars {
3306            if self.expr_mentions_var(vp, donkey_var) {
3307                body = self.ctx.exprs.alloc(LogicExpr::Quantifier {
3308                    kind: if kind.restricts_by_implication() {
3309                        QuantifierKind::Universal
3310                    } else {
3311                        QuantifierKind::Existential
3312                    },
3313                    variable: donkey_var,
3314                    body,
3315                    island_id: self.current_island,
3316                });
3317            }
3318        }
3319
3320        Ok(self.ctx.exprs.alloc(LogicExpr::Quantifier {
3321            kind,
3322            variable: var_name,
3323            body,
3324            island_id: self.current_island,
3325        }))
3326    }
3327
3328    /// Rebuild `expr` with free occurrences of variable `from` renamed to
3329    /// `to`; binders that shadow `from` keep their bodies untouched.
3330    fn rename_var_in_expr(
3331        &self,
3332        expr: &'a LogicExpr<'a>,
3333        from: Symbol,
3334        to: Symbol,
3335    ) -> &'a LogicExpr<'a> {
3336        let rename_term = |t: &Term<'a>| -> Term<'a> {
3337            match t {
3338                Term::Variable(v) if *v == from => Term::Variable(to),
3339                other => other.clone(),
3340            }
3341        };
3342        match expr {
3343            LogicExpr::Predicate { name, args, world } => {
3344                let new_args: Vec<Term<'a>> = args.iter().map(|a| rename_term(a)).collect();
3345                self.ctx.exprs.alloc(LogicExpr::Predicate {
3346                    name: *name,
3347                    args: self.ctx.terms.alloc_slice(new_args),
3348                    world: world.clone(),
3349                })
3350            }
3351            LogicExpr::Identity { left, right } => self.ctx.exprs.alloc(LogicExpr::Identity {
3352                left: self.ctx.terms.alloc(rename_term(left)),
3353                right: self.ctx.terms.alloc(rename_term(right)),
3354            }),
3355            LogicExpr::NeoEvent(data) => {
3356                let new_roles: Vec<(ThematicRole, Term<'a>)> = data
3357                    .roles
3358                    .iter()
3359                    .map(|(role, term)| (*role, rename_term(term)))
3360                    .collect();
3361                self.ctx
3362                    .exprs
3363                    .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
3364                        event_var: data.event_var,
3365                        verb: data.verb,
3366                        roles: self.ctx.roles.alloc_slice(new_roles),
3367                        modifiers: data.modifiers,
3368                        suppress_existential: data.suppress_existential,
3369                        world: data.world.clone(),
3370                    })))
3371            }
3372            LogicExpr::BinaryOp { left, op, right } => self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3373                left: self.rename_var_in_expr(left, from, to),
3374                op: op.clone(),
3375                right: self.rename_var_in_expr(right, from, to),
3376            }),
3377            LogicExpr::UnaryOp { op, operand } => self.ctx.exprs.alloc(LogicExpr::UnaryOp {
3378                op: op.clone(),
3379                operand: self.rename_var_in_expr(operand, from, to),
3380            }),
3381            LogicExpr::Quantifier {
3382                kind,
3383                variable,
3384                body,
3385                island_id,
3386            } if *variable != from => self.ctx.exprs.alloc(LogicExpr::Quantifier {
3387                kind: *kind,
3388                variable: *variable,
3389                body: self.rename_var_in_expr(body, from, to),
3390                island_id: *island_id,
3391            }),
3392            LogicExpr::Temporal { operator, body } => self.ctx.exprs.alloc(LogicExpr::Temporal {
3393                operator: *operator,
3394                body: self.rename_var_in_expr(body, from, to),
3395            }),
3396            LogicExpr::Aspectual { operator, body } => self.ctx.exprs.alloc(LogicExpr::Aspectual {
3397                operator: *operator,
3398                body: self.rename_var_in_expr(body, from, to),
3399            }),
3400            LogicExpr::Event { predicate, adverbs } => self.ctx.exprs.alloc(LogicExpr::Event {
3401                predicate: self.rename_var_in_expr(predicate, from, to),
3402                adverbs: *adverbs,
3403            }),
3404            other => other,
3405        }
3406    }
3407
3408    /// Collect variables that occur free in `expr` (not bound by an inner
3409    /// quantifier and not in `bound`), in first-occurrence order.
3410    fn collect_unbound_vars(
3411        &self,
3412        expr: &LogicExpr<'a>,
3413        bound: &mut Vec<Symbol>,
3414        out: &mut Vec<Symbol>,
3415    ) {
3416        fn term_vars(term: &Term<'_>, bound: &[Symbol], out: &mut Vec<Symbol>) {
3417            match term {
3418                Term::Variable(v) => {
3419                    if !bound.contains(v) && !out.contains(v) {
3420                        out.push(*v);
3421                    }
3422                }
3423                Term::Function(_, args) => {
3424                    for t in args.iter() {
3425                        term_vars(t, bound, out);
3426                    }
3427                }
3428                _ => {}
3429            }
3430        }
3431
3432        match expr {
3433            LogicExpr::Predicate { args, .. } => {
3434                for t in args.iter() {
3435                    term_vars(t, bound, out);
3436                }
3437            }
3438            LogicExpr::NeoEvent(data) => {
3439                for (_, t) in data.roles.iter() {
3440                    term_vars(t, bound, out);
3441                }
3442            }
3443            LogicExpr::BinaryOp { left, right, .. } => {
3444                self.collect_unbound_vars(left, bound, out);
3445                self.collect_unbound_vars(right, bound, out);
3446            }
3447            LogicExpr::UnaryOp { operand, .. } => self.collect_unbound_vars(operand, bound, out),
3448            LogicExpr::Quantifier { variable, body, .. } => {
3449                bound.push(*variable);
3450                self.collect_unbound_vars(body, bound, out);
3451                bound.pop();
3452            }
3453            LogicExpr::Temporal { body, .. } => self.collect_unbound_vars(body, bound, out),
3454            LogicExpr::Aspectual { body, .. } => self.collect_unbound_vars(body, bound, out),
3455            LogicExpr::Event { predicate, .. } => self.collect_unbound_vars(predicate, bound, out),
3456            LogicExpr::Modal { operand, .. } => self.collect_unbound_vars(operand, bound, out),
3457            LogicExpr::Scopal { body, .. } => self.collect_unbound_vars(body, bound, out),
3458            _ => {}
3459        }
3460    }
3461
3462    /// Check if an expression mentions a specific variable
3463    fn expr_mentions_var(&self, expr: &LogicExpr<'a>, var: Symbol) -> bool {
3464        match expr {
3465            LogicExpr::Predicate { args, .. } => {
3466                args.iter().any(|term| self.term_mentions_var(term, var))
3467            }
3468            LogicExpr::BinaryOp { left, right, .. } => {
3469                self.expr_mentions_var(left, var) || self.expr_mentions_var(right, var)
3470            }
3471            LogicExpr::UnaryOp { operand, .. } => self.expr_mentions_var(operand, var),
3472            LogicExpr::Quantifier { body, .. } => self.expr_mentions_var(body, var),
3473            LogicExpr::NeoEvent(data) => data
3474                .roles
3475                .iter()
3476                .any(|(_, term)| self.term_mentions_var(term, var)),
3477            LogicExpr::Temporal { body, .. } => self.expr_mentions_var(body, var),
3478            LogicExpr::Aspectual { body, .. } => self.expr_mentions_var(body, var),
3479            LogicExpr::Event { predicate, .. } => self.expr_mentions_var(predicate, var),
3480            LogicExpr::Modal { operand, .. } => self.expr_mentions_var(operand, var),
3481            LogicExpr::Scopal { body, .. } => self.expr_mentions_var(body, var),
3482            _ => false,
3483        }
3484    }
3485
3486    fn term_mentions_var(&self, term: &Term<'a>, var: Symbol) -> bool {
3487        match term {
3488            Term::Variable(v) => *v == var,
3489            Term::Function(_, args) => args.iter().any(|t| self.term_mentions_var(t, var)),
3490            _ => false,
3491        }
3492    }
3493
3494    /// Collect all conjuncts from a conjunction tree
3495    fn collect_conjuncts(&self, expr: &'a LogicExpr<'a>) -> Vec<&'a LogicExpr<'a>> {
3496        match expr {
3497            LogicExpr::BinaryOp {
3498                left,
3499                op: TokenType::And,
3500                right,
3501            } => {
3502                let mut result = self.collect_conjuncts(left);
3503                result.extend(self.collect_conjuncts(right));
3504                result
3505            }
3506            _ => vec![expr],
3507        }
3508    }
3509
3510    /// Wrap unused donkey bindings inside the restriction/body of a quantifier structure.
3511    ///
3512    /// For universals (implications):
3513    ///   Transform: ∀x((P(x) ∧ Q(y)) → R(x)) with unused y
3514    ///   Into:      ∀x((P(x) ∧ ∃y(Q(y))) → R(x))
3515    ///
3516    /// For existentials (conjunctions):
3517    ///   Transform: ∃x(P(x) ∧ Q(y) ∧ R(x)) with unused y
3518    ///   Into:      ∃x(P(x) ∧ ∃y(Q(y)) ∧ R(x))
3519    ///
3520    /// If wide_scope_negation is true, wrap the existential in negation:
3521    ///   Into:      ∀x((P(x) ∧ ¬∃y(Q(y))) → R(x))
3522    fn wrap_donkey_in_restriction(
3523        &self,
3524        body: &'a LogicExpr<'a>,
3525        donkey_var: Symbol,
3526        wide_scope_negation: bool,
3527    ) -> &'a LogicExpr<'a> {
3528        // Handle Quantifier wrapping first
3529        if let LogicExpr::Quantifier {
3530            kind,
3531            variable,
3532            body: inner_body,
3533            island_id,
3534        } = body
3535        {
3536            let transformed =
3537                self.wrap_donkey_in_restriction(inner_body, donkey_var, wide_scope_negation);
3538            return self.ctx.exprs.alloc(LogicExpr::Quantifier {
3539                kind: kind.clone(),
3540                variable: *variable,
3541                body: transformed,
3542                island_id: *island_id,
3543            });
3544        }
3545
3546        // Handle implication (universal quantifiers)
3547        if let LogicExpr::BinaryOp {
3548            left,
3549            op: TokenType::Implies,
3550            right,
3551        } = body
3552        {
3553            return self.wrap_in_implication(*left, *right, donkey_var, wide_scope_negation);
3554        }
3555
3556        // Handle conjunction (existential quantifiers)
3557        if let LogicExpr::BinaryOp {
3558            left: _,
3559            op: TokenType::And,
3560            right: _,
3561        } = body
3562        {
3563            return self.wrap_in_conjunction(body, donkey_var, wide_scope_negation);
3564        }
3565
3566        // Not a structure we can process
3567        body
3568    }
3569
3570    /// Wrap donkey binding in an implication structure (∀x(P(x) → Q(x)))
3571    fn wrap_in_implication(
3572        &self,
3573        restriction: &'a LogicExpr<'a>,
3574        consequent: &'a LogicExpr<'a>,
3575        donkey_var: Symbol,
3576        wide_scope_negation: bool,
3577    ) -> &'a LogicExpr<'a> {
3578        // Collect all conjuncts in the restriction
3579        let conjuncts = self.collect_conjuncts(restriction);
3580
3581        // Partition into those mentioning the donkey var and those not
3582        let (with_var, without_var): (Vec<_>, Vec<_>) = conjuncts
3583            .into_iter()
3584            .partition(|c| self.expr_mentions_var(c, donkey_var));
3585
3586        if with_var.is_empty() {
3587            // Variable not found in restriction, return original implication
3588            return self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3589                left: restriction,
3590                op: TokenType::Implies,
3591                right: consequent,
3592            });
3593        }
3594
3595        // Combine the "with var" conjuncts
3596        let with_var_combined = self.combine_conjuncts(&with_var);
3597
3598        // Wrap with existential
3599        let existential = self.ctx.exprs.alloc(LogicExpr::Quantifier {
3600            kind: QuantifierKind::Existential,
3601            variable: donkey_var,
3602            body: with_var_combined,
3603            island_id: self.current_island,
3604        });
3605
3606        // For wide scope negation (de dicto reading of "lacks"), wrap ∃ in ¬
3607        let wrapped = if wide_scope_negation {
3608            self.ctx.exprs.alloc(LogicExpr::UnaryOp {
3609                op: TokenType::Not,
3610                operand: existential,
3611            })
3612        } else {
3613            existential
3614        };
3615
3616        // Combine with "without var" conjuncts
3617        let new_restriction = if without_var.is_empty() {
3618            wrapped
3619        } else {
3620            let without_combined = self.combine_conjuncts(&without_var);
3621            self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3622                left: without_combined,
3623                op: TokenType::And,
3624                right: wrapped,
3625            })
3626        };
3627
3628        // Rebuild the implication
3629        self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3630            left: new_restriction,
3631            op: TokenType::Implies,
3632            right: consequent,
3633        })
3634    }
3635
3636    /// Wrap donkey binding in a conjunction structure (∃x(P(x) ∧ Q(x)))
3637    fn wrap_in_conjunction(
3638        &self,
3639        body: &'a LogicExpr<'a>,
3640        donkey_var: Symbol,
3641        wide_scope_negation: bool,
3642    ) -> &'a LogicExpr<'a> {
3643        // Collect all conjuncts
3644        let conjuncts = self.collect_conjuncts(body);
3645
3646        // Partition into those mentioning the donkey var and those not
3647        let (with_var, without_var): (Vec<_>, Vec<_>) = conjuncts
3648            .into_iter()
3649            .partition(|c| self.expr_mentions_var(c, donkey_var));
3650
3651        if with_var.is_empty() {
3652            // Variable not found, return unchanged
3653            return body;
3654        }
3655
3656        // Combine the "with var" conjuncts
3657        let with_var_combined = self.combine_conjuncts(&with_var);
3658
3659        // Wrap with existential
3660        let existential = self.ctx.exprs.alloc(LogicExpr::Quantifier {
3661            kind: QuantifierKind::Existential,
3662            variable: donkey_var,
3663            body: with_var_combined,
3664            island_id: self.current_island,
3665        });
3666
3667        // For wide scope negation (de dicto reading of "lacks"), wrap ∃ in ¬
3668        let wrapped = if wide_scope_negation {
3669            self.ctx.exprs.alloc(LogicExpr::UnaryOp {
3670                op: TokenType::Not,
3671                operand: existential,
3672            })
3673        } else {
3674            existential
3675        };
3676
3677        // Combine with "without var" conjuncts
3678        if without_var.is_empty() {
3679            wrapped
3680        } else {
3681            let without_combined = self.combine_conjuncts(&without_var);
3682            self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3683                left: without_combined,
3684                op: TokenType::And,
3685                right: wrapped,
3686            })
3687        }
3688    }
3689
3690    fn combine_conjuncts(&self, conjuncts: &[&'a LogicExpr<'a>]) -> &'a LogicExpr<'a> {
3691        if conjuncts.is_empty() {
3692            panic!("Cannot combine empty conjuncts");
3693        }
3694        if conjuncts.len() == 1 {
3695            return conjuncts[0];
3696        }
3697        let mut result = conjuncts[0];
3698        for c in &conjuncts[1..] {
3699            result = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3700                left: result,
3701                op: TokenType::And,
3702                right: *c,
3703            });
3704        }
3705        result
3706    }
3707}