Skip to main content

logicaffeine_language/parser/
verb.rs

1//! Verb phrase parsing with event semantics and thematic roles.
2//!
3//! This module handles the core verbal predication including:
4//!
5//! - **Intransitive verbs**: "John runs" → `∃e(Run(e) ∧ Agent(e,John))`
6//! - **Transitive verbs**: "John loves Mary" → `∃e(Love(e) ∧ Agent(e,John) ∧ Theme(e,Mary))`
7//! - **Ditransitive verbs**: "John gives Mary a book" → with Goal role
8//! - **Copula constructions**: "John is tall", "John is a doctor"
9//! - **Control verbs**: "John wants to run" → raising/control structures
10//! - **Plural subjects**: "John and Mary run", "John and Mary love each other"
11//! - **VP respectively**: "John and Mary love Sue and Bill respectively"
12//!
13//! # Neo-Davidsonian Event Semantics
14//!
15//! Verbs introduce event variables with thematic roles:
16//! - **Agent**: The doer of the action
17//! - **Theme/Patient**: The entity affected
18//! - **Goal/Recipient**: The target of transfer
19//! - **Instrument**: The tool used
20//!
21//! Events are represented using `LogicExpr::NeoEvent` with a verb symbol and
22//! a list of (ThematicRole, Term) pairs.
23
24use super::clause::ClauseParsing;
25use super::modal::ModalParsing;
26use super::noun::NounParsing;
27use super::pragmatics::PragmaticsParsing;
28use super::quantifier::QuantifierParsing;
29use super::{IndefiniteScope, ParseResult, Parser};
30use crate::ast::{
31    AspectOperator, LogicExpr, NeoEventData, NounPhrase, QuantifierKind, TemporalOperator, Term,
32    ThematicRole,
33};
34use crate::drs::{Gender, Number, ReferentSource};
35use crate::error::{ParseError, ParseErrorKind};
36use crate::lexer::Lexer;
37use crate::lexicon::{Aspect, Definiteness, Time};
38use crate::token::{FocusKind, Token, TokenType};
39use logicaffeine_base::Symbol;
40
41use crate::ast::Stmt;
42
43/// Trait for parsing verb phrases in declarative (logic) mode.
44///
45/// Provides methods for parsing predicates with subjects, control verbs,
46/// and plural/group constructions with Neo-Davidsonian event semantics.
47pub trait LogicVerbParsing<'a, 'ctx, 'int> {
48    /// Parses a verb phrase given the subject as a constant symbol.
49    fn parse_predicate_with_subject(
50        &mut self,
51        subject_symbol: Symbol,
52    ) -> ParseResult<&'a LogicExpr<'a>>;
53    /// Parses a verb phrase with subject as a bound variable.
54    fn parse_predicate_with_subject_as_var(
55        &mut self,
56        subject_symbol: Symbol,
57    ) -> ParseResult<&'a LogicExpr<'a>>;
58    /// Attempts to parse a plural subject ("John and Mary verb").
59    /// Returns `Ok(Some(expr))` on success, `Ok(None)` if not plural, `Err` on semantic error.
60    fn try_parse_plural_subject(
61        &mut self,
62        first_subject: &NounPhrase<'a>,
63    ) -> Result<Option<&'a LogicExpr<'a>>, ParseError>;
64    /// Parses control verb structures: "wants to VP", "persuaded X to VP".
65    fn parse_control_structure(
66        &mut self,
67        subject: &NounPhrase<'a>,
68        verb: Symbol,
69        verb_time: Time,
70    ) -> ParseResult<&'a LogicExpr<'a>>;
71    /// Checks if a verb is a control verb (want, try, persuade, etc.).
72    fn is_control_verb(&self, verb: Symbol) -> bool;
73    /// Builds a predicate for intransitive verbs with multiple subjects.
74    fn build_group_predicate(
75        &mut self,
76        subjects: &[Symbol],
77        verb: Symbol,
78        verb_time: Time,
79    ) -> &'a LogicExpr<'a>;
80    /// Builds a transitive predicate with group subject and group object.
81    fn build_group_transitive(
82        &mut self,
83        subjects: &[Symbol],
84        objects: &[Symbol],
85        verb: Symbol,
86        verb_time: Time,
87    ) -> &'a LogicExpr<'a>;
88}
89
90/// Trait for parsing verb phrases in imperative (LOGOS) mode.
91///
92/// Provides methods for parsing statements rather than logical propositions.
93pub trait ImperativeVerbParsing<'a, 'ctx, 'int> {
94    /// Parses a statement with the given subject symbol.
95    fn parse_statement_with_subject(&mut self, subject_symbol: Symbol) -> ParseResult<Stmt<'a>>;
96}
97
98impl<'a, 'ctx, 'int> Parser<'a, 'ctx, 'int> {
99    /// Nominal copula predication: the body of "SUBJ is (the) PRED-NP".
100    ///
101    /// The subject is identified with the predicate nominal, so every property
102    /// of the predicate NP is predicated of the SUBJECT term:
103    /// `Pred(subj) ∧ Adj_i(subj) ∧ [Possesses(possessor, subj)]`, recursing
104    /// through the possessor's own possessor chain. This keeps the genitive
105    /// constraint — "X is the Alvarado family's house" entails the Alvarado
106    /// family possesses X — instead of dropping it.
107    pub(super) fn nominal_predication(
108        &mut self,
109        subject_term: Term<'a>,
110        pred_np: &NounPhrase<'a>,
111    ) -> &'a LogicExpr<'a> {
112        let mut result = self.ctx.exprs.alloc(LogicExpr::Predicate {
113            name: pred_np.noun,
114            args: self.ctx.terms.alloc_slice([subject_term]),
115            world: None,
116        });
117
118        for &adj in pred_np.adjectives {
119            let adj_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
120                name: adj,
121                args: self.ctx.terms.alloc_slice([subject_term]),
122                world: None,
123            });
124            result = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
125                left: result,
126                op: TokenType::And,
127                right: adj_pred,
128            });
129        }
130
131        if let Some(possessor) = pred_np.possessor {
132            let poss_logic = self.possessor_predication(possessor, subject_term);
133            result = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
134                left: result,
135                op: TokenType::And,
136                right: poss_logic,
137            });
138        }
139
140        result
141    }
142
143    /// THE single decision point for whether a possessor / passive-by-agent NP
144    /// refers by a bare constant or must become its own restrictor-carrying entity.
145    /// Returns the term that stands for the possessor/agent in the relation, plus
146    /// (when descriptive) the fresh variable and the restrictor that scopes it:
147    ///   - a **bare** NP (no adjectives, no nested genitive, no PPs — "Agnes",
148    ///     "His", "John's") → `(Term::Constant(np.noun), None)`, the referring
149    ///     constant, so its output is byte-identical to the historical form;
150    ///   - a **descriptive** NP ("the old captain", "the Woodard family", "the red
151    ///     team") → `(Term::Variable(pvar), Some((pvar, restrictor)))` where the
152    ///     restrictor is `nominal_predication(Variable(pvar), np)` conjoined with
153    ///     each of the NP's PPs (substituted onto `pvar`), so EVERY modifier
154    ///     survives instead of collapsing to the bare head.
155    ///
156    /// The restrictor recurses through [`Self::nominal_predication`] (which re-enters
157    /// [`Self::possessor_entity`] for a nested genitive), so an arbitrarily deep
158    /// "X's B's C" is handled uniformly. Callers wrap the relation they build over
159    /// the returned term with [`Self::wrap_in_possessor_entity`].
160    pub(super) fn possessor_entity(
161        &mut self,
162        np: &NounPhrase<'a>,
163    ) -> (Term<'a>, Option<(Symbol, &'a LogicExpr<'a>)>) {
164        let is_descriptive =
165            !np.adjectives.is_empty() || np.possessor.is_some() || !np.pps.is_empty();
166        if !is_descriptive {
167            return (Term::Constant(np.noun), None);
168        }
169        let pvar = self.next_var_name();
170        let mut restr = self.nominal_predication(Term::Variable(pvar), np);
171        for pp in np.pps {
172            let pp_sub = self.substitute_pp_placeholder(pp, pvar);
173            restr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
174                left: restr,
175                op: TokenType::And,
176                right: pp_sub,
177            });
178        }
179        (Term::Variable(pvar), Some((pvar, restr)))
180    }
181
182    /// Scope a relation built over a possessor/agent term inside that entity's
183    /// existential, when [`Self::possessor_entity`] produced a restrictor:
184    ///   - `None` (bare possessor/agent) → `relation` unchanged;
185    ///   - `Some((pvar, restrictor))` → `∃pvar(restrictor ∧ relation)`.
186    pub(super) fn wrap_in_possessor_entity(
187        &mut self,
188        restr: Option<(Symbol, &'a LogicExpr<'a>)>,
189        relation: &'a LogicExpr<'a>,
190    ) -> &'a LogicExpr<'a> {
191        match restr {
192            None => relation,
193            Some((pvar, restrictor)) => {
194                let body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
195                    left: restrictor,
196                    op: TokenType::And,
197                    right: relation,
198                });
199                self.ctx.exprs.alloc(LogicExpr::Quantifier {
200                    kind: QuantifierKind::Existential,
201                    variable: pvar,
202                    body,
203                    island_id: self.current_island,
204                })
205            }
206        }
207    }
208
209    /// Lower a possessor noun phrase to its logical contribution, predicating it of
210    /// `possessed_term`. THE single place a genitive becomes logic, so a possessor's
211    /// adjectives / nested genitive / PPs survive in EVERY syntactic position rather
212    /// than each construction re-deriving (and dropping) them:
213    ///   - a **descriptive** possessor ("the old captain", "X's B") → its own
214    ///     existential entity carrying its full restrictor, recursively lowered:
215    ///     `∃p(Restrictor(p) ∧ Possesses(p, possessed))`;
216    ///   - a **bare** proper name ("Agnes") → the referring constant:
217    ///     `Possesses(Agnes, possessed)`.
218    pub(super) fn possessor_predication(
219        &mut self,
220        possessor: &NounPhrase<'a>,
221        possessed_term: Term<'a>,
222    ) -> &'a LogicExpr<'a> {
223        let (poss_term, restr) = self.possessor_entity(possessor);
224        let possesses = self.ctx.exprs.alloc(LogicExpr::Predicate {
225            name: self.interner.intern("Possesses"),
226            args: self.ctx.terms.alloc_slice([poss_term, possessed_term]),
227            world: None,
228        });
229        self.wrap_in_possessor_entity(restr, possesses)
230    }
231
232    /// Like [`Self::nominal_predication`] but ALSO conjoins the NP's PPs / reduced
233    /// relatives (the `_PP_SELF_` placeholder substituted to `subject_term`,
234    /// whether a constant or a variable). Use at sites that predicate a full NP of
235    /// a term and would otherwise drop "the medicine sourced from a fig" down to
236    /// `Medicine(x)`. Does NOT double-count at sites that already loop the PPs.
237    pub(super) fn nominal_predication_with_pps(
238        &mut self,
239        subject_term: Term<'a>,
240        pred_np: &NounPhrase<'a>,
241    ) -> &'a LogicExpr<'a> {
242        let mut result = self.nominal_predication(subject_term, pred_np);
243        for pp in pred_np.pps {
244            // Recurse through the restrictor's structure so a COMPLEX pp — a reduced
245            // relative built as a NeoEvent / quantified conjunction, not just a flat
246            // Predicate — has its `_PP_SELF_` gap bound and is NOT silently dropped.
247            let pp_sub = self.substitute_pp_self_term(pp, subject_term);
248            result = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
249                left: result,
250                op: TokenType::And,
251                right: pp_sub,
252            });
253        }
254        result
255    }
256
257    /// THE single place a PP object's own modifiers are recovered: its ADJECTIVES
258    /// ("the BIG table") and nested Predicate PPs ("a range OF 650 ft"), each
259    /// predicated of the object constant (nested PPs' `_PP_SELF_` rebound to it).
260    /// Every PP position (NP-internal, copula, passive-agent, modal) routes through
261    /// this so "on the BIG table" / "by the LOCAL police" never drop the modifier.
262    pub(super) fn pp_object_modifier_preds(
263        &mut self,
264        pp_object: &NounPhrase<'a>,
265    ) -> Vec<&'a LogicExpr<'a>> {
266        let mut out: Vec<&'a LogicExpr<'a>> = Vec::new();
267        for &adj in pp_object.adjectives {
268            out.push(self.ctx.exprs.alloc(LogicExpr::Predicate {
269                name: adj,
270                args: self.ctx.terms.alloc_slice([Term::Constant(pp_object.noun)]),
271                world: None,
272            }));
273        }
274        let placeholder = self.interner.intern("_PP_SELF_");
275        for nested in pp_object.pps {
276            if let LogicExpr::Predicate { name, args, world } = nested {
277                let new_args: Vec<Term<'a>> = args
278                    .iter()
279                    .map(|a| match a {
280                        Term::Variable(v) if *v == placeholder => Term::Constant(pp_object.noun),
281                        other => *other,
282                    })
283                    .collect();
284                out.push(self.ctx.exprs.alloc(LogicExpr::Predicate {
285                    name: *name,
286                    args: self.ctx.terms.alloc_slice(new_args),
287                    world: *world,
288                }));
289            }
290        }
291        out
292    }
293
294    /// Conjoin a PP object's recovered modifiers (see [`Self::pp_object_modifier_preds`])
295    /// onto `pred` — for PP sites that build a single conjoined relation (copula,
296    /// passive-agent, modal) rather than a `pps` list.
297    pub(super) fn attach_pp_object_modifiers(
298        &mut self,
299        mut pred: &'a LogicExpr<'a>,
300        pp_object: &NounPhrase<'a>,
301    ) -> &'a LogicExpr<'a> {
302        for m in self.pp_object_modifier_preds(pp_object) {
303            pred = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
304                left: pred,
305                op: TokenType::And,
306                right: m,
307            });
308        }
309        pred
310    }
311
312    /// Consume trailing EVENT PP-adjuncts ("takes a holiday WITH a friend TO some
313    /// location") and conjoin each as `Prep(event, obj)` onto `event`. The
314    /// non-quantified object path consumes these inline in its main PP loop; the
315    /// QUANTIFIED-object path wraps the event in `∃`, so without this the PPs strand
316    /// as trailing tokens. A bare preposition with no object is handed back for the
317    /// sentence-level parse to report rather than silently dropped.
318    pub(super) fn attach_trailing_event_pps(
319        &mut self,
320        mut event: &'a LogicExpr<'a>,
321        event_var: Symbol,
322    ) -> ParseResult<&'a LogicExpr<'a>> {
323        while self.check_preposition() || self.check_to() {
324            // "within N <unit>" is a temporal bound, not a PP.
325            if self.check_preposition_is("within")
326                && matches!(
327                    self.tokens.get(self.current + 1).map(|t| &t.kind),
328                    Some(TokenType::Cardinal(_)) | Some(TokenType::Number(_))
329                )
330            {
331                break;
332            }
333            // An NP object must follow; otherwise leave the preposition in place.
334            let object_follows = matches!(
335                self.tokens.get(self.current + 1).map(|t| &t.kind),
336                Some(TokenType::Article(_))
337                    | Some(TokenType::Noun(_))
338                    | Some(TokenType::ProperName(_))
339                    | Some(TokenType::All)
340                    | Some(TokenType::Some)
341                    | Some(TokenType::Any)
342                    | Some(TokenType::Cardinal(_))
343                    | Some(TokenType::Number(_))
344                    | Some(TokenType::Pronoun { .. })
345            );
346            if !object_follows {
347                break;
348            }
349            let prep_token = self.advance().clone();
350            let prep_name = match prep_token.kind {
351                TokenType::Preposition(sym) => sym,
352                TokenType::To => self.interner.intern("To"),
353                _ => break,
354            };
355            // A quantified PP object ("to SOME new location", "with ANY friend")
356            // leads with a bare quantifier token that parse_noun_phrase does not
357            // consume; drop it so the head noun reads as the object referent. The
358            // PP object is represented by its noun constant, matching the indefinite
359            // ("with a friend" → With(e, Friend)) convention.
360            if matches!(
361                self.peek().kind,
362                TokenType::Some | TokenType::Any | TokenType::All | TokenType::No
363            ) {
364                self.advance();
365            }
366            let pp_np = self.parse_noun_phrase(false)?;
367            let pp_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
368                name: prep_name,
369                args: self
370                    .ctx
371                    .terms
372                    .alloc_slice([Term::Variable(event_var), Term::Constant(pp_np.noun)]),
373                world: None,
374            });
375            event = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
376                left: event,
377                op: TokenType::And,
378                right: pp_pred,
379            });
380        }
381        Ok(event)
382    }
383
384    /// Substitute the `_PP_SELF_` placeholder with `term` (constant OR variable)
385    /// throughout a restrictor, recursing through connectives / quantifiers / events.
386    /// Generalizes [`QuantifierParsing::substitute_pp_placeholder`] (which targets a
387    /// variable) so a reduced-relative restrictor binds its gap wherever it sits.
388    pub(super) fn substitute_pp_self_term(
389        &mut self,
390        pp: &'a LogicExpr<'a>,
391        term: Term<'a>,
392    ) -> &'a LogicExpr<'a> {
393        let placeholder = self.interner.intern("_PP_SELF_");
394        match pp {
395            LogicExpr::Predicate { name, args, .. } => {
396                let new_args: Vec<Term<'a>> = args
397                    .iter()
398                    .map(|a| match a {
399                        Term::Variable(v) if *v == placeholder => term,
400                        other => *other,
401                    })
402                    .collect();
403                self.ctx.exprs.alloc(LogicExpr::Predicate {
404                    name: *name,
405                    args: self.ctx.terms.alloc_slice(new_args),
406                    world: None,
407                })
408            }
409            LogicExpr::BinaryOp { left, op, right } => {
410                let l = self.substitute_pp_self_term(left, term);
411                let r = self.substitute_pp_self_term(right, term);
412                self.ctx.exprs.alloc(LogicExpr::BinaryOp {
413                    left: l,
414                    op: op.clone(),
415                    right: r,
416                })
417            }
418            LogicExpr::UnaryOp { op, operand } => {
419                let o = self.substitute_pp_self_term(operand, term);
420                self.ctx.exprs.alloc(LogicExpr::UnaryOp {
421                    op: op.clone(),
422                    operand: o,
423                })
424            }
425            LogicExpr::Quantifier {
426                kind,
427                variable,
428                body,
429                island_id,
430            } => {
431                let b = self.substitute_pp_self_term(body, term);
432                self.ctx.exprs.alloc(LogicExpr::Quantifier {
433                    kind: *kind,
434                    variable: *variable,
435                    body: b,
436                    island_id: *island_id,
437                })
438            }
439            LogicExpr::Temporal { operator, body } => {
440                let b = self.substitute_pp_self_term(body, term);
441                self.ctx.exprs.alloc(LogicExpr::Temporal {
442                    operator: *operator,
443                    body: b,
444                })
445            }
446            LogicExpr::NeoEvent(data) => {
447                let new_roles: Vec<(ThematicRole, Term<'a>)> = data
448                    .roles
449                    .iter()
450                    .map(|(role, t)| {
451                        let nt = match t {
452                            Term::Variable(v) if *v == placeholder => term,
453                            other => *other,
454                        };
455                        (*role, nt)
456                    })
457                    .collect();
458                self.ctx
459                    .exprs
460                    .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
461                        event_var: data.event_var,
462                        verb: data.verb,
463                        roles: self.ctx.roles.alloc_slice(new_roles),
464                        modifiers: data.modifiers,
465                        suppress_existential: data.suppress_existential,
466                        world: data.world,
467                    })))
468            }
469            _ => pp,
470        }
471    }
472
473    /// If a relative clause ("WHO played", "THAT won 9 games") trails a predicate
474    /// nominal, conjoin it onto `pred`, predicated of the subject — "X is the
475    /// player who played" entails X played. The gap binds to the subject term
476    /// (constant or variable). A no-op when no relative clause follows. Shared by
477    /// every copula-complement site (plain `is the Y`, `either A or B`,
478    /// neither/nor, quantified subjects) so the feature composes once.
479    /// If a relativizer follows, parse the relative clause over `term` and return it.
480    /// One place so who/that (argument gap), where (locative), and whose (possessive)
481    /// compose UNIFORMLY at every NP attachment site (subject, predicate nominal,
482    /// either-or / of-pair member, comparison/temporal standard) instead of each site
483    /// re-checking who/that inline and silently stranding where/whose. The where/whose
484    /// helpers consume their own relativizer; parse_relative_clause expects who/that
485    /// already consumed (matching its existing callers).
486    pub(super) fn try_attach_relative(
487        &mut self,
488        term: Term<'a>,
489    ) -> ParseResult<Option<&'a LogicExpr<'a>>> {
490        if let Term::Constant(s) | Term::Variable(s) = term {
491            if self.check(&TokenType::Who) || self.check(&TokenType::That) {
492                self.advance();
493                return Ok(Some(self.parse_relative_clause(s)?));
494            } else if self.check(&TokenType::Where) {
495                return Ok(Some(self.parse_where_relative(s)?));
496            } else if self.check(&TokenType::Whose) {
497                return Ok(Some(self.parse_whose_relative(s)?));
498            }
499        }
500        Ok(None)
501    }
502
503    pub(super) fn conjoin_trailing_relative(
504        &mut self,
505        pred: &'a LogicExpr<'a>,
506        subject_term: Term<'a>,
507    ) -> ParseResult<&'a LogicExpr<'a>> {
508        let mut pred = pred;
509        // who/that/where/whose relative on the complement.
510        if let Some(rc) = self.try_attach_relative(subject_term.clone())? {
511            pred = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
512                left: pred,
513                op: TokenType::And,
514                right: rc,
515            });
516        }
517        // A REDUCED relative ("is the mountain FIRST CLIMBED in 1845", "is the island
518        // SEEN by Captain Norris") — every caller is a copula complement / predicate
519        // nominal / disjunct, where the copula is already consumed, so a trailing
520        // participle is a reduced relative restricting the subject, never a matrix verb.
521        if let Some(rr) = self.try_consume_reduced_relative(subject_term)? {
522            pred = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
523                left: pred,
524                op: TokenType::And,
525                right: rr,
526            });
527        }
528        Ok(pred)
529    }
530
531    /// Conjoin a temporal adverb consumed after a relative-clause copula ("who is NOW
532    /// with the Tigers") over the gap, or return the predication unchanged when there
533    /// was no adverb. Shared by the progressive and the predicate-complement exits of
534    /// the copular relative branch.
535    pub(super) fn conjoin_relative_temporal_adverb(
536        &mut self,
537        pred: &'a LogicExpr<'a>,
538        gap_var: Symbol,
539        adv: Option<Symbol>,
540    ) -> &'a LogicExpr<'a> {
541        match adv {
542            Some(a) => {
543                let adv_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
544                    name: a,
545                    args: self.ctx.terms.alloc_slice([Term::Variable(gap_var)]),
546                    world: None,
547                });
548                self.ctx.exprs.alloc(LogicExpr::BinaryOp {
549                    left: pred,
550                    op: TokenType::And,
551                    right: adv_pred,
552                })
553            }
554            None => pred,
555        }
556    }
557
558    /// Copula complement led by a temporal/ordinal adverb: "was FIRST" (ranked
559    /// first), "is NOW the leader", "was THEN the champion". Returns the base
560    /// predication over `subject_term` — the adverb conjoined with any following
561    /// predicate nominal/adjective ("is now THE LEADER" → Leader(x) ∧ Now(x)), or the
562    /// bare adverb when it is the whole complement ("was first" → First(x)). Returns
563    /// None when the next token is not a temporal adverb, so the caller falls through
564    /// to its other complement branches. The caller applies its own tense / negation /
565    /// definiteness wrapping. Restricted to TemporalAdverb so a degree adverb ("is
566    /// very tall") is not mis-attached to the subject. Shared by parse_atom and
567    /// parse_predicate so both copula paths gain the reading from one place.
568    pub(super) fn copula_temporal_adverb_complement(
569        &mut self,
570        subject_term: Term<'a>,
571    ) -> ParseResult<Option<&'a LogicExpr<'a>>> {
572        let adv = match self.peek().kind {
573            TokenType::TemporalAdverb(s) => s,
574            _ => return Ok(None),
575        };
576        self.advance();
577        let adv_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
578            name: adv,
579            args: self.ctx.terms.alloc_slice([subject_term.clone()]),
580            world: None,
581        });
582        if self.check_article() || self.check_content_word() {
583            let saved_ctx = self.nominal_np_context;
584            self.nominal_np_context = true;
585            let comp_np_result = self.parse_noun_phrase(true);
586            self.nominal_np_context = saved_ctx;
587            let comp_np = comp_np_result?;
588            let comp_pred = self.nominal_predication_with_pps(subject_term.clone(), &comp_np);
589            let comp_pred = self.conjoin_trailing_relative(comp_pred, subject_term.clone())?;
590            return Ok(Some(self.ctx.exprs.alloc(LogicExpr::BinaryOp {
591                left: comp_pred,
592                op: TokenType::And,
593                right: adv_pred,
594            })));
595        }
596        Ok(Some(adv_pred))
597    }
598
599    /// Apply the copula's tense, negation, and temporal-adverb wrappers to a
600    /// finished predication body, in the same order the bare-predicate path uses.
601    pub(super) fn finish_copula(
602        &self,
603        base: &'a LogicExpr<'a>,
604        copula_time: Time,
605        is_negated: bool,
606        copula_temporal: Option<super::CopulaTemporal>,
607    ) -> &'a LogicExpr<'a> {
608        let with_time = if copula_time == Time::Past {
609            self.ctx.exprs.alloc(LogicExpr::Temporal {
610                operator: TemporalOperator::Past,
611                body: base,
612            })
613        } else {
614            base
615        };
616        let with_neg = if is_negated {
617            self.ctx.exprs.alloc(LogicExpr::UnaryOp {
618                op: TokenType::Not,
619                operand: with_time,
620            })
621        } else {
622            with_time
623        };
624        match copula_temporal {
625            Some(super::CopulaTemporal::Always) => self.ctx.exprs.alloc(LogicExpr::Temporal {
626                operator: TemporalOperator::Always,
627                body: with_neg,
628            }),
629            Some(super::CopulaTemporal::Never) => {
630                let negated = self.ctx.exprs.alloc(LogicExpr::UnaryOp {
631                    op: TokenType::Not,
632                    operand: with_time,
633                });
634                self.ctx.exprs.alloc(LogicExpr::Temporal {
635                    operator: TemporalOperator::Always,
636                    body: negated,
637                })
638            }
639            Some(super::CopulaTemporal::Eventually) => self.ctx.exprs.alloc(LogicExpr::Temporal {
640                operator: TemporalOperator::Eventually,
641                body: with_neg,
642            }),
643            None => with_neg,
644        }
645    }
646
647    /// Arithmetic / vague verbal comparative after a just-consumed verb.
648    ///
649    /// Matches `[MEASURE] [DEGREE] COMPARATIVE "than" STANDARD`, where the verb
650    /// names the graded dimension (its event is asserted), a measure phrase
651    /// ("3 points") is the exact offset, and a degree modifier ("somewhat")
652    /// marks a strict-but-imprecise inequality. The bare "faster than Bob" case
653    /// (no measure, no degree modifier) is left for the caller. Returns `None`
654    /// without consuming when the pattern is absent.
655    pub(super) fn try_arithmetic_comparative(
656        &mut self,
657        verb: Symbol,
658        subject_term: Term<'a>,
659        verb_time: Time,
660    ) -> ParseResult<Option<&'a LogicExpr<'a>>> {
661        let is_unit = |k: &TokenType| {
662            matches!(
663                k,
664                TokenType::Noun(_)
665                    | TokenType::Adjective(_)
666                    | TokenType::NonIntersectiveAdjective(_)
667                    | TokenType::Verb { .. }
668                    | TokenType::ProperName(_)
669                    | TokenType::Performative(_)
670                    | TokenType::Ambiguous { .. }
671                    // Measure-unit tokens ("10 more MINUTES than", "3 ounces more
672                    // gold than") — a calendar/clock unit or duration literal heads
673                    // the comparison dimension just like a plain unit noun.
674                    | TokenType::CalendarUnit(_)
675                    | TokenType::DurationLiteral { .. }
676            )
677        };
678        let cp = self.checkpoint();
679
680        // 0. A price/measure comparative may be introduced by "for"/"at"/"with"
681        // ("sold for $25,000 less than Y", "sold for somewhat less than Y",
682        // "finished with 3 ounces more gold than Y"). Tentatively drop it; the
683        // checkpoint restores it if no comparative follows, so a plain "sold for
684        // $105" / "finished with a medal" still flows to the PP handler.
685        if matches!(self.peek().kind, TokenType::Preposition(s)
686            if matches!(self.interner.resolve(s).to_lowercase().as_str(), "for" | "at" | "with"))
687        {
688            self.advance();
689        }
690
691        // 0b. A possessed-quality comparative is introduced by an indefinite
692        // article ("has a narrower wingspan than Y", "has a 4 inches narrower
693        // wingspan than Y"). Tentatively drop it; the checkpoint restores it if no
694        // comparative follows, so a plain "has a wingspan" still flows onward.
695        if matches!(
696            self.peek().kind,
697            TokenType::Article(crate::lexicon::Definiteness::Indefinite)
698        ) {
699            self.advance();
700        }
701
702        // 1. Optional numeric offset ("3", "190").
703        let count_kind: Option<crate::ast::NumberKind> = match self.peek().kind {
704            TokenType::Number(s) => {
705                self.advance();
706                // The one numeral rule, shared with the measure phrase and the
707                // comparison target: an `i64` is the integer it denotes, a well-formed
708                // decimal is a `Real`, and anything else keeps its lexeme rather than
709                // falling to a value it does not have.
710                Some(super::pragmatics::parse_number_kind(
711                    self.interner.resolve(s),
712                    s,
713                ))
714            }
715            TokenType::Cardinal(n) => {
716                self.advance();
717                Some(crate::ast::NumberKind::Integer(n as i64))
718            }
719            _ => None,
720        };
721
722        // 2. Optional unit noun BEFORE the comparative ("3 points lower").
723        let mut unit_sym: Option<Symbol> = None;
724        if count_kind.is_some()
725            && is_unit(&self.peek().kind)
726            && matches!(
727                self.tokens.get(self.current + 1).map(|t| &t.kind),
728                Some(TokenType::Comparative(_))
729            )
730        {
731            unit_sym = Some(self.consume_content_word()?);
732        }
733
734        // 3. A dimension noun and/or degree modifier between here and the comparative.
735        // A NOUN ("a wingspan LONGER than", "a face WIDER than") is the comparison
736        // DIMENSION → unit_sym, so the measure is Wingspan(x)/Wingspan(y) and not the
737        // verb (the prenominal form "a LONGER wingspan than" puts the comparative first
738        // and is captured at step 5). A non-noun degree word ("somewhat", "much") is
739        // discarded. Both may appear ("a wingspan SOMEWHAT longer than"). Only the
740        // count-less case — the numeric "4 inches narrower" path is handled at step 2.
741        let mut has_vague = false;
742        if unit_sym.is_none() && count_kind.is_none() {
743            // Pure lookahead (no checkpoint side effects): scan dimension noun(s), an
744            // optional degree adverb, and require a Comparative to follow. Only then
745            // consume — so a bare object ("won her prize") with no comparative is
746            // untouched.
747            let mut k = self.current;
748            while self.tokens.get(k).map_or(false, |t| {
749                matches!(t.kind, TokenType::Noun(_) | TokenType::Ambiguous { .. })
750                    && !crate::lexicon::is_degree_adverb(
751                        &self.interner.resolve(t.lexeme).to_lowercase(),
752                    )
753            }) {
754                k += 1;
755            }
756            let dim_end = k;
757            let has_dim = dim_end > self.current;
758            let degree = !matches!(
759                self.tokens.get(k).map(|t| &t.kind),
760                Some(TokenType::Comparative(_))
761            ) && matches!(
762                self.tokens.get(k + 1).map(|t| &t.kind),
763                Some(TokenType::Comparative(_))
764            );
765            let comp_at = if degree { k + 1 } else { k };
766            let comp_here = matches!(
767                self.tokens.get(comp_at).map(|t| &t.kind),
768                Some(TokenType::Comparative(_))
769            );
770            if has_dim && comp_here {
771                let mut dim: Option<Symbol> = None;
772                while self.current < dim_end {
773                    let n = self.consume_content_word()?;
774                    dim = Some(match dim {
775                        Some(d) => self.interner.intern(&format!(
776                            "{}_{}",
777                            self.interner.resolve(d),
778                            self.interner.resolve(n)
779                        )),
780                        None => n,
781                    });
782                }
783                if degree {
784                    self.advance(); // degree adverb (discarded)
785                    has_vague = true;
786                }
787                unit_sym = dim;
788            }
789        }
790        // 3b. A bare degree modifier with no dimension noun ("somewhat higher").
791        if unit_sym.is_none()
792            && !matches!(self.peek().kind, TokenType::Comparative(_))
793            && matches!(
794                self.tokens.get(self.current + 1).map(|t| &t.kind),
795                Some(TokenType::Comparative(_))
796            )
797        {
798            self.advance(); // degree modifier
799            has_vague = true;
800        }
801
802        // 4. The comparative itself.
803        let comp_adj = match self.peek().kind {
804            TokenType::Comparative(a) => {
805                self.advance();
806                a
807            }
808            _ => {
809                self.restore(cp);
810                return Ok(None);
811            }
812        };
813
814        // 5. A unit / dimension noun phrase AFTER the comparative, immediately before
815        // "than" ("1 more game than", "less baking time than", "received 7 votes more
816        // votes than Ken"). Consume the WHOLE (possibly multi-word) dimension up to
817        // "than"; join multi-word into one measure symbol ("baking time" → Baking_time)
818        // so the prover relates the same dimension. A unit already captured before the
819        // comparative makes a post-comparative noun redundant — consumed but discarded.
820        {
821            let mut k = self.current;
822            while self.tokens.get(k).map_or(false, |t| is_unit(&t.kind)) {
823                k += 1;
824            }
825            let unit_end = k;
826            // An infinitive purpose modifier on the dimension ("10 more minutes TO
827            // PRINT than") specifies what the measured amount is FOR; fold the verb
828            // into the dimension so the prover relates the same measure on both sides
829            // ("minutes to print" → Minute_print).
830            let infinitive: Option<Symbol> = if unit_end > self.current
831                && matches!(
832                    self.tokens.get(unit_end).map(|t| &t.kind),
833                    Some(TokenType::To)
834                ) {
835                match self.tokens.get(unit_end + 1).map(|t| t.kind.clone()) {
836                    Some(TokenType::Verb { lemma, .. }) => Some(lemma),
837                    _ => None,
838                }
839            } else {
840                None
841            };
842            let after = if infinitive.is_some() {
843                unit_end + 2
844            } else {
845                unit_end
846            };
847            if unit_end > self.current
848                && matches!(
849                    self.tokens.get(after).map(|t| &t.kind),
850                    Some(TokenType::Than)
851                )
852            {
853                let mut dim = self.consume_content_word()?;
854                while self.current < unit_end {
855                    let next = self.consume_content_word()?;
856                    dim = self.interner.intern(&format!(
857                        "{}_{}",
858                        self.interner.resolve(dim),
859                        self.interner.resolve(next)
860                    ));
861                }
862                if let Some(vlemma) = infinitive {
863                    self.advance(); // "to"
864                    self.advance(); // the infinitive verb
865                    dim = self.interner.intern(&format!(
866                        "{}_{}",
867                        self.interner.resolve(dim),
868                        self.interner.resolve(vlemma)
869                    ));
870                }
871                if unit_sym.is_none() {
872                    unit_sym = Some(dim);
873                }
874            }
875        }
876
877        // 5b. A per-unit RATE between the comparative and "than" ("less per gallon
878        // than", "5 dollars less per pound than", "10 dollars less per month than")
879        // — the comparison is on a RATE, not a raw amount. The basis is folded into
880        // the measure name (Charge → Charge_per_Gallon) so the prover relates
881        // per-gallon prices; the count's noun ("dollars") becomes the offset unit.
882        let mut rate_unit: Option<Symbol> = None;
883        if matches!(self.peek().kind, TokenType::Preposition(s)
884            if self.interner.resolve(s).eq_ignore_ascii_case("per"))
885        {
886            let cp_rate = self.checkpoint();
887            self.advance(); // "per"
888            if is_unit(&self.peek().kind) {
889                rate_unit = Some(self.consume_content_word()?);
890            } else {
891                self.restore(cp_rate);
892            }
893        }
894
895        // 6. "than" must follow. A measure prefix (count or degree) makes this an
896        // exact/vague arithmetic comparative. A BARE comparative ("cost less than
897        // the potatoes") is also a genuine comparison — handled here for a
898        // solver-ready `Less`/`Greater` over a DISTINCT standard entity — EXCEPT
899        // when the standard is a number ("ate more than 5 apples" is a quantity,
900        // not an entity comparison), which is left for the quantity path.
901        if !matches!(self.peek().kind, TokenType::Than) {
902            self.restore(cp);
903            return Ok(None);
904        }
905        if count_kind.is_none() && !has_vague {
906            // A QUANTIFIED standard ("more than 5 apples" = quantity; "faster than
907            // all cats" = a universally-quantified comparison) is not a bare
908            // entity comparison — leave it for the quantity / verbal-comparative
909            // quantifier paths.
910            let standard_quantified = self
911                .tokens
912                .get(self.current + 1)
913                .map(|t| &t.kind)
914                .is_some_and(|t| t.is_generalized_quantifier())
915                || matches!(
916                    self.tokens.get(self.current + 1).map(|t| &t.kind),
917                    Some(TokenType::Number(_))
918                        | Some(TokenType::Cardinal(_))
919                        | Some(TokenType::All)
920                        | Some(TokenType::No)
921                        | Some(TokenType::Some)
922                        | Some(TokenType::Any)
923                        | Some(TokenType::AtLeast(_))
924                        | Some(TokenType::AtMost(_))
925                );
926            if standard_quantified {
927                self.restore(cp);
928                return Ok(None);
929            }
930        }
931        self.advance(); // "than"
932
933        let event_var = self.get_event_var();
934        let mut modifiers = Vec::new();
935        let effective_time = self.pending_time.take().unwrap_or(verb_time);
936        match effective_time {
937            Time::Past => modifiers.push(self.interner.intern("Past")),
938            Time::Future => modifiers.push(self.interner.intern("Future")),
939            _ => {}
940        }
941        let suppress_existential = self.drs.in_conditional_antecedent();
942        let event = self
943            .ctx
944            .exprs
945            .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
946                event_var,
947                verb,
948                roles: self
949                    .ctx
950                    .roles
951                    .alloc_slice(vec![(ThematicRole::Agent, subject_term)]),
952                modifiers: self.ctx.syms.alloc_slice(modifiers),
953                suppress_existential,
954                world: None,
955            })));
956
957        // Solver-ready arithmetic: a measure function over the entity, an
958        // arithmetic offset (add/sub — the names the LIA oracle recognises), and
959        // an equality (exact) or strict inequality (vague). The measure is named
960        // by the unit ("points" → Points) or, lacking one, by the verb ("scored"
961        // → Score) — stable across both sides so the prover can relate them.
962        let cap = |s: &str| -> String {
963            let mut c = s.chars();
964            match c.next() {
965                Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
966                None => String::new(),
967            }
968        };
969        let measure_name = match (rate_unit, unit_sym) {
970            // A rate names the measure by the VERB per the rate unit; the count's
971            // noun ("dollars") is the offset's unit, not the measure name.
972            (Some(r), _) => format!(
973                "{}_per_{}",
974                cap(&self.interner.resolve(verb).to_string()),
975                cap(&self.interner.resolve(r).to_string())
976            ),
977            (None, Some(u)) => cap(&self.interner.resolve(u).to_string()),
978            (None, None) => cap(&self.interner.resolve(verb).to_string()),
979        };
980        let measure_sym = self.interner.intern(&measure_name);
981        // `comp_adj` is the base adjective lemma (e.g. "narrow", "short"); its scale
982        // polarity decides the direction. Negative-pole adjectives subtract.
983        let comp_str = self.interner.resolve(comp_adj).to_lowercase();
984        let subtract = crate::lexicon::is_decreasing_adjective(&comp_str);
985        let op_sym = self.interner.intern(if subtract { "sub" } else { "add" });
986        let dir_sym = self
987            .interner
988            .intern(if subtract { "Less" } else { "Greater" });
989        // For a rate ("5 dollars less per gallon"), the count's noun is the
990        // offset's currency unit; otherwise the count is implicitly in the measure.
991        let offset_unit = if rate_unit.is_some() { unit_sym } else { None };
992        let offset_term: Option<Term<'a>> = count_kind.map(|kind| Term::Value {
993            kind,
994            unit: offset_unit,
995            dimension: None,
996        });
997        let measure_x = Term::Function(measure_sym, self.ctx.terms.alloc_slice([subject_term]));
998        let build_constraint = move |p: &mut Self, y_term: Term<'a>| -> &'a LogicExpr<'a> {
999            let measure_y = Term::Function(measure_sym, p.ctx.terms.alloc_slice([y_term]));
1000            match offset_term {
1001                Some(off) => {
1002                    let rhs = Term::Function(op_sym, p.ctx.terms.alloc_slice([measure_y, off]));
1003                    p.ctx.exprs.alloc(LogicExpr::Identity {
1004                        left: p.ctx.terms.alloc(measure_x),
1005                        right: p.ctx.terms.alloc(rhs),
1006                    })
1007                }
1008                None => p.ctx.exprs.alloc(LogicExpr::Predicate {
1009                    name: dir_sym,
1010                    args: p.ctx.terms.alloc_slice([measure_x, measure_y]),
1011                    world: None,
1012                }),
1013            }
1014        };
1015
1016        // The standard of comparison. A DESCRIPTION (determiner / adjective /
1017        // possessor / PP / relative clause) becomes its own existentially
1018        // quantified entity carrying a restrictor — so "less than Quinn Quade's
1019        // stamp" does NOT collapse onto the subject's "Stamp" constant (which
1020        // would make `Less(Sell(Stamp), Sell(Stamp))` — the subject compared to
1021        // itself — and misattach the possessor to the subject). A bare proper
1022        // name stays a referring constant. Greedy parse so a PP standard ("than
1023        // the perfume from Spain") attaches its PP. A comparative standard is a
1024        // nominal position — "than" rules out the matrix verb — so a verb-word
1025        // head in it is a deverbal noun ("than the orange PACK", "the investing
1026        // SHOW").
1027        let saved_ctx = self.nominal_np_context;
1028        self.nominal_np_context = true;
1029        let std_np_result = self.parse_noun_phrase(true);
1030        self.nominal_np_context = saved_ctx;
1031        let std_np = std_np_result?;
1032        let has_rel = self.check(&TokenType::Who) || self.check(&TokenType::That);
1033        let is_desc = has_rel
1034            || std_np.definiteness.is_some()
1035            || !std_np.adjectives.is_empty()
1036            || std_np.possessor.is_some()
1037            || !std_np.pps.is_empty();
1038        let result = if is_desc {
1039            let std_var = self.next_var_name();
1040            // Head noun + adjectives + possessor over the standard's variable.
1041            let mut restr = self.nominal_predication(Term::Variable(std_var), &std_np);
1042            for pp in std_np.pps {
1043                let pp_sub = self.substitute_pp_placeholder(pp, std_var);
1044                restr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1045                    left: restr,
1046                    op: TokenType::And,
1047                    right: pp_sub,
1048                });
1049            }
1050            if has_rel {
1051                self.advance(); // "who" / "that"
1052                let rel = self.parse_relative_clause(std_var)?;
1053                restr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1054                    left: restr,
1055                    op: TokenType::And,
1056                    right: rel,
1057                });
1058            }
1059            let comparison = build_constraint(self, Term::Variable(std_var));
1060            let body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1061                left: restr,
1062                op: TokenType::And,
1063                right: comparison,
1064            });
1065            let quantified = self.ctx.exprs.alloc(LogicExpr::Quantifier {
1066                kind: QuantifierKind::Existential,
1067                variable: std_var,
1068                body,
1069                island_id: self.current_island,
1070            });
1071            self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1072                left: event,
1073                op: TokenType::And,
1074                right: quantified,
1075            })
1076        } else {
1077            let comparison = build_constraint(self, Term::Constant(std_np.noun));
1078            self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1079                left: event,
1080                op: TokenType::And,
1081                right: comparison,
1082            })
1083        };
1084        Ok(Some(result))
1085    }
1086
1087    /// Temporal offset after a just-consumed verb: `COUNT CALENDAR-UNIT
1088    /// (after|before) STANDARD` ("performed 2 weeks after Bessie", "will launch
1089    /// 2 months before the graduate who will be studying radiation"). The verb
1090    /// event is asserted and a directed offset relates the subject to the
1091    /// standard. Returns `None` without consuming when the pattern is absent.
1092    /// Bare temporal ordering "(sometime) before/after STANDARD" relating
1093    /// `subject_term` DIRECTLY to a distinct standard entity by time — used by the
1094    /// PASSIVE path ("the photo was taken sometime before the photo of the red
1095    /// panda", "was bought sometime before Faye's pet"), which has no NeoEvent var.
1096    /// Returns `Before/After(subject_term, std)` with the standard a distinct
1097    /// ∃-entity (descriptive) or a constant (bare name). `None` (no consumption) if
1098    /// the pattern is absent. A leading vague adverb ("sometime") is skipped.
1099    pub(super) fn parse_bare_temporal_constraint(
1100        &mut self,
1101        subject_term: Term<'a>,
1102    ) -> ParseResult<Option<&'a LogicExpr<'a>>> {
1103        let j = self.current;
1104        let std_at = |k: Option<&TokenType>| {
1105            matches!(
1106                k,
1107                Some(TokenType::Article(_))
1108                    | Some(TokenType::Noun(_))
1109                    | Some(TokenType::ProperName(_))
1110            )
1111        };
1112        let lead_adverb = match self.tokens.get(j).map(|t| &t.kind) {
1113            Some(TokenType::Adverb(_)) => true,
1114            Some(_) => matches!(
1115                self.interner
1116                    .resolve(self.tokens[j].lexeme)
1117                    .to_lowercase()
1118                    .as_str(),
1119                "sometime" | "shortly" | "soon" | "immediately" | "long" | "right" | "just"
1120            ),
1121            None => false,
1122        };
1123        let dj = if lead_adverb { j + 1 } else { j };
1124        let next_kind = self.tokens.get(dj + 1).map(|t| &t.kind);
1125        // A YEAR or clock time is also a valid temporal reference ("won a prize BEFORE
1126        // 1989", "started AFTER 2010") — the prover orders the value against other
1127        // years/times. Accept a numeric/time-literal object alongside the NP object.
1128        let temporal_at = |k: Option<&TokenType>| {
1129            std_at(k)
1130                || matches!(
1131                    k,
1132                    Some(TokenType::Number(_)) | Some(TokenType::TimeLiteral { .. })
1133                )
1134        };
1135        let bare_dir = match self.tokens.get(dj).map(|t| &t.kind) {
1136            Some(TokenType::Before) if temporal_at(next_kind) => Some("Before"),
1137            Some(TokenType::Preposition(s))
1138                if self.interner.resolve(*s).eq_ignore_ascii_case("before")
1139                    && temporal_at(next_kind) =>
1140            {
1141                Some("Before")
1142            }
1143            Some(TokenType::Preposition(s))
1144                if self.interner.resolve(*s).eq_ignore_ascii_case("after")
1145                    && temporal_at(next_kind) =>
1146            {
1147                Some("After")
1148            }
1149            _ => None,
1150        };
1151        let dir = match bare_dir {
1152            Some(d) => d,
1153            None => return Ok(None),
1154        };
1155        if lead_adverb {
1156            self.advance();
1157        }
1158        self.advance(); // "before" / "after"
1159        let rel_sym = self.interner.intern(dir);
1160        // Numeric temporal reference ("before 1989", "after 2010", "before 9:30am"):
1161        // the year/clock-time is a value, so relate the subject to it directly.
1162        if matches!(
1163            self.peek().kind,
1164            TokenType::Number(_) | TokenType::TimeLiteral { .. }
1165        ) {
1166            let year = self.parse_measure_phrase()?;
1167            return Ok(Some(self.ctx.exprs.alloc(LogicExpr::Predicate {
1168                name: rel_sym,
1169                args: self.ctx.terms.alloc_slice([subject_term, *year]),
1170                world: None,
1171            })));
1172        }
1173        let std_np = self.parse_noun_phrase(true)?;
1174        let has_rel = self.check(&TokenType::Who) || self.check(&TokenType::That);
1175        let is_desc = has_rel
1176            || std_np.definiteness.is_some()
1177            || !std_np.adjectives.is_empty()
1178            || std_np.possessor.is_some()
1179            || !std_np.pps.is_empty();
1180        let result = if is_desc {
1181            let v = self.next_var_name();
1182            let mut restr = self.nominal_predication(Term::Variable(v), &std_np);
1183            for pp in std_np.pps {
1184                let pp_sub = self.substitute_pp_placeholder(pp, v);
1185                restr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1186                    left: restr,
1187                    op: TokenType::And,
1188                    right: pp_sub,
1189                });
1190            }
1191            if has_rel {
1192                self.advance();
1193                let rel = self.parse_relative_clause(v)?;
1194                restr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1195                    left: restr,
1196                    op: TokenType::And,
1197                    right: rel,
1198                });
1199            }
1200            let rel = self.ctx.exprs.alloc(LogicExpr::Predicate {
1201                name: rel_sym,
1202                args: self
1203                    .ctx
1204                    .terms
1205                    .alloc_slice([subject_term, Term::Variable(v)]),
1206                world: None,
1207            });
1208            let body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1209                left: restr,
1210                op: TokenType::And,
1211                right: rel,
1212            });
1213            self.ctx.exprs.alloc(LogicExpr::Quantifier {
1214                kind: QuantifierKind::Existential,
1215                variable: v,
1216                body,
1217                island_id: self.current_island,
1218            })
1219        } else {
1220            self.ctx.exprs.alloc(LogicExpr::Predicate {
1221                name: rel_sym,
1222                args: self
1223                    .ctx
1224                    .terms
1225                    .alloc_slice([subject_term, Term::Constant(std_np.noun)]),
1226                world: None,
1227            })
1228        };
1229        Ok(Some(result))
1230    }
1231
1232    pub(super) fn try_temporal_offset(
1233        &mut self,
1234        verb: Symbol,
1235        subject_term: Term<'a>,
1236        verb_time: Time,
1237    ) -> ParseResult<Option<&'a LogicExpr<'a>>> {
1238        let j = self.current;
1239
1240        // Bare temporal ordering (no count/unit): "<verb> before STANDARD" or
1241        // "<verb> after THE/A STANDARD" — relate the subject's event to a
1242        // DISTINCT standard entity. "after <proper name>" is intentionally left
1243        // to the PP-adjunct path (which already yields After(e, Name)); only the
1244        // gaps ("before …", "after the/a …") are filled here.
1245        let std_at = |k: Option<&TokenType>| {
1246            matches!(
1247                k,
1248                Some(TokenType::Article(_))
1249                    | Some(TokenType::Noun(_))
1250                    | Some(TokenType::ProperName(_))
1251            )
1252        };
1253        // A vague temporal adverb may precede the direction ("starts SOMETIME
1254        // after …", "arrived SHORTLY before …"); it only emphasises the absence
1255        // of a precise offset, which the bare relation already captures, so skip
1256        // it. `dj` indexes the after/before once it is skipped.
1257        let lead_adverb = match self.tokens.get(j).map(|t| &t.kind) {
1258            Some(TokenType::Adverb(_)) => true,
1259            Some(_) => matches!(
1260                self.interner
1261                    .resolve(self.tokens[j].lexeme)
1262                    .to_lowercase()
1263                    .as_str(),
1264                "sometime" | "shortly" | "soon" | "immediately" | "long" | "right" | "just"
1265            ),
1266            None => false,
1267        };
1268        let dj = if lead_adverb { j + 1 } else { j };
1269        let next_kind = self.tokens.get(dj + 1).map(|t| &t.kind);
1270        // A YEAR or clock time is a temporal reference the prover can order ("happened
1271        // BEFORE 1989", "started AFTER 2010"). "after <name>" still defers to the
1272        // PP-adjunct path, but "after <year>" has no such path, so accept it here.
1273        let num_at = |k: Option<&TokenType>| {
1274            matches!(
1275                k,
1276                Some(TokenType::Number(_)) | Some(TokenType::TimeLiteral { .. })
1277            )
1278        };
1279        let bare_dir = match self.tokens.get(dj).map(|t| &t.kind) {
1280            Some(TokenType::Before) if std_at(next_kind) || num_at(next_kind) => Some("Before"),
1281            Some(TokenType::Preposition(s))
1282                if self.interner.resolve(*s).eq_ignore_ascii_case("before")
1283                    && (std_at(next_kind) || num_at(next_kind)) =>
1284            {
1285                Some("Before")
1286            }
1287            Some(TokenType::Preposition(s))
1288                if self.interner.resolve(*s).eq_ignore_ascii_case("after")
1289                    && (matches!(next_kind, Some(TokenType::Article(_))) || num_at(next_kind)) =>
1290            {
1291                Some("After")
1292            }
1293            _ => None,
1294        };
1295        if let Some(dir) = bare_dir {
1296            if lead_adverb {
1297                self.advance(); // skip the vague temporal adverb
1298            }
1299            self.advance(); // "before" / "after"
1300            let event_var = self.get_event_var();
1301            let mut modifiers = Vec::new();
1302            let effective_time = self.pending_time.take().unwrap_or(verb_time);
1303            match effective_time {
1304                Time::Past => modifiers.push(self.interner.intern("Past")),
1305                Time::Future => modifiers.push(self.interner.intern("Future")),
1306                _ => {}
1307            }
1308            let suppress_existential = self.drs.in_conditional_antecedent();
1309            let event = self
1310                .ctx
1311                .exprs
1312                .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
1313                    event_var,
1314                    verb,
1315                    roles: self
1316                        .ctx
1317                        .roles
1318                        .alloc_slice(vec![(ThematicRole::Agent, subject_term)]),
1319                    modifiers: self.ctx.syms.alloc_slice(modifiers),
1320                    suppress_existential,
1321                    world: None,
1322                })));
1323            let rel_sym = self.interner.intern(dir);
1324            // Numeric temporal reference ("happened before 1989", "started after
1325            // 2010"): relate the EVENT to the year/clock-time value directly.
1326            if matches!(
1327                self.peek().kind,
1328                TokenType::Number(_) | TokenType::TimeLiteral { .. }
1329            ) {
1330                let year = self.parse_measure_phrase()?;
1331                let rel = self.ctx.exprs.alloc(LogicExpr::Predicate {
1332                    name: rel_sym,
1333                    args: self
1334                        .ctx
1335                        .terms
1336                        .alloc_slice([Term::Variable(event_var), *year]),
1337                    world: None,
1338                });
1339                return Ok(Some(self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1340                    left: event,
1341                    op: TokenType::And,
1342                    right: rel,
1343                })));
1344            }
1345            // A temporal standard ("after the skydiving TRIP") is a nominal
1346            // position — a verb-word head there is a deverbal noun.
1347            let saved_ctx = self.nominal_np_context;
1348            self.nominal_np_context = true;
1349            let std_np_result = self.parse_noun_phrase(true);
1350            self.nominal_np_context = saved_ctx;
1351            let std_np = std_np_result?;
1352            let is_desc = std_np.definiteness.is_some()
1353                || !std_np.adjectives.is_empty()
1354                || std_np.possessor.is_some()
1355                || !std_np.pps.is_empty();
1356            let result = if is_desc {
1357                let v = self.next_var_name();
1358                let mut restr = self.nominal_predication(Term::Variable(v), &std_np);
1359                for pp in std_np.pps {
1360                    let pp_sub = self.substitute_pp_placeholder(pp, v);
1361                    restr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1362                        left: restr,
1363                        op: TokenType::And,
1364                        right: pp_sub,
1365                    });
1366                }
1367                // A relative clause on the standard ("before the winner WHO won in
1368                // chemistry", "after the person WHO took the cruise") restricts the
1369                // standard entity; without this it was stranded (TrailingTokens at
1370                // Who/That). Mirrors parse_bare_temporal_constraint and the offset path.
1371                if self.check(&TokenType::Who) || self.check(&TokenType::That) {
1372                    self.advance();
1373                    let rc = self.parse_relative_clause(v)?;
1374                    restr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1375                        left: restr,
1376                        op: TokenType::And,
1377                        right: rc,
1378                    });
1379                }
1380                let rel = self.ctx.exprs.alloc(LogicExpr::Predicate {
1381                    name: rel_sym,
1382                    args: self
1383                        .ctx
1384                        .terms
1385                        .alloc_slice([Term::Variable(event_var), Term::Variable(v)]),
1386                    world: None,
1387                });
1388                let body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1389                    left: restr,
1390                    op: TokenType::And,
1391                    right: rel,
1392                });
1393                let quant = self.ctx.exprs.alloc(LogicExpr::Quantifier {
1394                    kind: QuantifierKind::Existential,
1395                    variable: v,
1396                    body,
1397                    island_id: self.current_island,
1398                });
1399                self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1400                    left: event,
1401                    op: TokenType::And,
1402                    right: quant,
1403                })
1404            } else {
1405                let rel = self.ctx.exprs.alloc(LogicExpr::Predicate {
1406                    name: rel_sym,
1407                    args: self
1408                        .ctx
1409                        .terms
1410                        .alloc_slice([Term::Variable(event_var), Term::Constant(std_np.noun)]),
1411                    world: None,
1412                });
1413                self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1414                    left: event,
1415                    op: TokenType::And,
1416                    right: rel,
1417                })
1418            };
1419            return Ok(Some(result));
1420        }
1421
1422        // "N <unit> after/before STANDARD" — a solver-ready measure offset. The
1423        // event is asserted and a constraint relates the two positions. The
1424        // constraint builder is shared with the PASSIVE path ("was taken 1 month
1425        // after Y"), which already has its own event, so it is factored out into
1426        // `parse_temporal_offset_constraint`.
1427        let has_count = matches!(
1428            self.tokens.get(j).map(|t| &t.kind),
1429            Some(TokenType::Number(_)) | Some(TokenType::Cardinal(_))
1430        );
1431        let has_unit = matches!(
1432            self.tokens.get(j + 1).map(|t| &t.kind),
1433            Some(TokenType::CalendarUnit(_))
1434        );
1435        let has_dir = matches!(
1436            self.tokens.get(j + 2).map(|t| &t.kind),
1437            Some(TokenType::Before)
1438        ) || matches!(self.tokens.get(j + 2).map(|t| &t.kind),
1439                Some(TokenType::Preposition(s))
1440                    if matches!(self.interner.resolve(*s).to_lowercase().as_str(), "after" | "before"));
1441        if !(has_count && has_unit && has_dir) {
1442            return Ok(None);
1443        }
1444
1445        // Capture tense BEFORE parsing the standard, whose relative clause could
1446        // otherwise overwrite pending_time.
1447        let effective_time = self.pending_time.take().unwrap_or(verb_time);
1448        let constraint = match self.parse_temporal_offset_constraint(subject_term)? {
1449            Some(c) => c,
1450            None => return Ok(None),
1451        };
1452        let event_var = self.get_event_var();
1453        let mut modifiers = Vec::new();
1454        match effective_time {
1455            Time::Past => modifiers.push(self.interner.intern("Past")),
1456            Time::Future => modifiers.push(self.interner.intern("Future")),
1457            _ => {}
1458        }
1459        let suppress_existential = self.drs.in_conditional_antecedent();
1460        let event = self
1461            .ctx
1462            .exprs
1463            .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
1464                event_var,
1465                verb,
1466                roles: self
1467                    .ctx
1468                    .roles
1469                    .alloc_slice(vec![(ThematicRole::Agent, subject_term)]),
1470                modifiers: self.ctx.syms.alloc_slice(modifiers),
1471                suppress_existential,
1472                world: None,
1473            })));
1474        Ok(Some(self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1475            left: event,
1476            op: TokenType::And,
1477            right: constraint,
1478        })))
1479    }
1480
1481    /// Parses a calendar-unit measure offset `N <unit> (after|before) STANDARD`
1482    /// positioned at the count, returning ONLY the solver-ready constraint
1483    /// `Unit(subject) = add|sub(Unit(STANDARD), N)` (after → add, before → sub).
1484    /// The caller supplies the event (active VP) or passive predicate it conjoins
1485    /// to. A descriptive standard becomes a distinct existential entity carrying
1486    /// its restrictor (head + adjectives + possessor + PPs + relative clause); a
1487    /// bare proper name stays a constant. `None` (no consumption) if the offset
1488    /// pattern is absent.
1489    pub(super) fn parse_temporal_offset_constraint(
1490        &mut self,
1491        subject_term: Term<'a>,
1492    ) -> ParseResult<Option<&'a LogicExpr<'a>>> {
1493        let j = self.current;
1494        let has_count = matches!(
1495            self.tokens.get(j).map(|t| &t.kind),
1496            Some(TokenType::Number(_)) | Some(TokenType::Cardinal(_))
1497        );
1498        let has_unit = matches!(
1499            self.tokens.get(j + 1).map(|t| &t.kind),
1500            Some(TokenType::CalendarUnit(_))
1501        );
1502        let direction = match self.tokens.get(j + 2).map(|t| &t.kind) {
1503            Some(TokenType::Before) => Some("Before"),
1504            Some(TokenType::Preposition(s)) => {
1505                match self.interner.resolve(*s).to_lowercase().as_str() {
1506                    "after" => Some("After"),
1507                    "before" => Some("Before"),
1508                    _ => None,
1509                }
1510            }
1511            _ => None,
1512        };
1513        if !(has_count && has_unit && direction.is_some()) {
1514            return Ok(None);
1515        }
1516        let direction = direction.unwrap();
1517
1518        // Offset count (Number or Cardinal) and calendar unit.
1519        let count_kind = match self.advance().kind {
1520            TokenType::Number(s) => {
1521                let raw = self.interner.resolve(s);
1522                if let Ok(n) = raw.parse::<i64>() {
1523                    crate::ast::NumberKind::Integer(n)
1524                } else {
1525                    crate::ast::NumberKind::Symbolic(s)
1526                }
1527            }
1528            TokenType::Cardinal(n) => crate::ast::NumberKind::Integer(n as i64),
1529            _ => unreachable!("guarded by has_count"),
1530        };
1531        let unit_lexeme = self.peek().lexeme;
1532        self.advance(); // calendar unit
1533        self.advance(); // "after" / "before"
1534
1535        let cap = |s: &str| -> String {
1536            let mut c = s.chars();
1537            match c.next() {
1538                Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
1539                None => String::new(),
1540            }
1541        };
1542        let measure_sym = self
1543            .interner
1544            .intern(&cap(&self.interner.resolve(unit_lexeme).to_string()));
1545        let op_sym = self
1546            .interner
1547            .intern(if direction == "After" { "add" } else { "sub" });
1548        let offset_term = Term::Value {
1549            kind: count_kind,
1550            unit: None,
1551            dimension: None,
1552        };
1553
1554        let measure_x = Term::Function(measure_sym, self.ctx.terms.alloc_slice([subject_term]));
1555        let build_constraint = move |p: &mut Self, y_term: Term<'a>| -> &'a LogicExpr<'a> {
1556            let measure_y = Term::Function(measure_sym, p.ctx.terms.alloc_slice([y_term]));
1557            let rhs = Term::Function(op_sym, p.ctx.terms.alloc_slice([measure_y, offset_term]));
1558            p.ctx.exprs.alloc(LogicExpr::Identity {
1559                left: p.ctx.terms.alloc(measure_x),
1560                right: p.ctx.terms.alloc(rhs),
1561            })
1562        };
1563
1564        // Distinct-identity treatment: a descriptive standard ("2 weeks after
1565        // Quinn Quade's debut") becomes its own existential entity so it never
1566        // collapses onto the subject and its possessor/PP/relative clause bind to
1567        // IT; a bare name stays a constant. The standard is nominal ("after"
1568        // rules out the matrix verb) → a verb-word head is a deverbal noun
1569        // ("1 month after the goblin shark PROJECT").
1570        let saved_ctx = self.nominal_np_context;
1571        self.nominal_np_context = true;
1572        let std_np_result = self.parse_noun_phrase(true);
1573        self.nominal_np_context = saved_ctx;
1574        let std_np = std_np_result?;
1575        let has_rel = self.check(&TokenType::Who) || self.check(&TokenType::That);
1576        let is_desc = has_rel
1577            || std_np.definiteness.is_some()
1578            || !std_np.adjectives.is_empty()
1579            || std_np.possessor.is_some()
1580            || !std_np.pps.is_empty();
1581        let result = if is_desc {
1582            let std_var = self.next_var_name();
1583            let mut restr = self.nominal_predication(Term::Variable(std_var), &std_np);
1584            for pp in std_np.pps {
1585                let pp_sub = self.substitute_pp_placeholder(pp, std_var);
1586                restr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1587                    left: restr,
1588                    op: TokenType::And,
1589                    right: pp_sub,
1590                });
1591            }
1592            if has_rel {
1593                self.advance(); // "who" / "that"
1594                let rel = self.parse_relative_clause(std_var)?;
1595                restr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1596                    left: restr,
1597                    op: TokenType::And,
1598                    right: rel,
1599                });
1600            }
1601            let relation = build_constraint(self, Term::Variable(std_var));
1602            let body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1603                left: restr,
1604                op: TokenType::And,
1605                right: relation,
1606            });
1607            self.ctx.exprs.alloc(LogicExpr::Quantifier {
1608                kind: QuantifierKind::Existential,
1609                variable: std_var,
1610                body,
1611                island_id: self.current_island,
1612            })
1613        } else {
1614            build_constraint(self, Term::Constant(std_np.noun))
1615        };
1616        Ok(Some(result))
1617    }
1618
1619    /// Ordinal-position offset after a just-consumed verb: `COUNT
1620    /// (place|places|spot|spots) (ahead of | behind | before | after) STANDARD`
1621    /// ("finished 2 places ahead of Bob", "performed 1 spot before Violet"). The
1622    /// verb event is asserted and a directed offset orders the two positions:
1623    /// `Place(X) = add|sub(Place(Y), N)` (ahead/before → sub, behind/after → add),
1624    /// solver-ready, with the standard as a DISTINCT entity. `None` if absent.
1625    pub(super) fn try_positional_offset(
1626        &mut self,
1627        verb: Symbol,
1628        subject_term: Term<'a>,
1629        verb_time: Time,
1630    ) -> ParseResult<Option<&'a LogicExpr<'a>>> {
1631        let j = self.current;
1632        let has_count = matches!(
1633            self.tokens.get(j).map(|t| &t.kind),
1634            Some(TokenType::Number(_)) | Some(TokenType::Cardinal(_))
1635        );
1636        let is_pos_unit = self
1637            .tokens
1638            .get(j + 1)
1639            .map(|t| {
1640                matches!(
1641                    self.interner.resolve(t.lexeme).to_lowercase().as_str(),
1642                    "place" | "places" | "spot" | "spots"
1643                )
1644            })
1645            .unwrap_or(false);
1646        if !(has_count && is_pos_unit) {
1647            return Ok(None);
1648        }
1649        // Direction word at j+2: ahead(/of) / before → sub; behind / after → add.
1650        let (subtract, ahead_of) = match self.tokens.get(j + 2).map(|t| &t.kind) {
1651            Some(TokenType::Before) => (true, false),
1652            Some(_) => match self
1653                .interner
1654                .resolve(self.tokens[j + 2].lexeme)
1655                .to_lowercase()
1656                .as_str()
1657            {
1658                "ahead" => (true, true),
1659                "before" => (true, false),
1660                "behind" => (false, false),
1661                "after" => (false, false),
1662                _ => return Ok(None),
1663            },
1664            None => return Ok(None),
1665        };
1666
1667        let count_kind = match self.advance().kind {
1668            TokenType::Number(s) => {
1669                let raw = self.interner.resolve(s);
1670                if let Ok(n) = raw.parse::<i64>() {
1671                    crate::ast::NumberKind::Integer(n)
1672                } else {
1673                    crate::ast::NumberKind::Symbolic(s)
1674                }
1675            }
1676            TokenType::Cardinal(n) => crate::ast::NumberKind::Integer(n as i64),
1677            _ => unreachable!("guarded by has_count"),
1678        };
1679        self.advance(); // positional unit
1680        self.advance(); // direction word
1681        if ahead_of
1682            && matches!(self.peek().kind, TokenType::Preposition(s)
1683                if self.interner.resolve(s).eq_ignore_ascii_case("of"))
1684        {
1685            self.advance(); // "of" after "ahead"
1686        }
1687
1688        let measure_sym = self.interner.intern("Place");
1689        let op_sym = self.interner.intern(if subtract { "sub" } else { "add" });
1690        let offset_term = Term::Value {
1691            kind: count_kind,
1692            unit: None,
1693            dimension: None,
1694        };
1695
1696        let event_var = self.get_event_var();
1697        let mut modifiers = Vec::new();
1698        let effective_time = self.pending_time.take().unwrap_or(verb_time);
1699        match effective_time {
1700            Time::Past => modifiers.push(self.interner.intern("Past")),
1701            Time::Future => modifiers.push(self.interner.intern("Future")),
1702            _ => {}
1703        }
1704        let suppress_existential = self.drs.in_conditional_antecedent();
1705        let event = self
1706            .ctx
1707            .exprs
1708            .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
1709                event_var,
1710                verb,
1711                roles: self
1712                    .ctx
1713                    .roles
1714                    .alloc_slice(vec![(ThematicRole::Agent, subject_term)]),
1715                modifiers: self.ctx.syms.alloc_slice(modifiers),
1716                suppress_existential,
1717                world: None,
1718            })));
1719
1720        let measure_x = Term::Function(measure_sym, self.ctx.terms.alloc_slice([subject_term]));
1721        let build_constraint = move |p: &mut Self, y_term: Term<'a>| -> &'a LogicExpr<'a> {
1722            let measure_y = Term::Function(measure_sym, p.ctx.terms.alloc_slice([y_term]));
1723            let rhs = Term::Function(op_sym, p.ctx.terms.alloc_slice([measure_y, offset_term]));
1724            p.ctx.exprs.alloc(LogicExpr::Identity {
1725                left: p.ctx.terms.alloc(measure_x),
1726                right: p.ctx.terms.alloc(rhs),
1727            })
1728        };
1729
1730        let std_np = self.parse_noun_phrase(true)?;
1731        let has_rel = self.check(&TokenType::Who) || self.check(&TokenType::That);
1732        let is_desc = has_rel
1733            || std_np.definiteness.is_some()
1734            || !std_np.adjectives.is_empty()
1735            || std_np.possessor.is_some()
1736            || !std_np.pps.is_empty();
1737        let result = if is_desc {
1738            let std_var = self.next_var_name();
1739            let mut restr = self.nominal_predication(Term::Variable(std_var), &std_np);
1740            for pp in std_np.pps {
1741                let pp_sub = self.substitute_pp_placeholder(pp, std_var);
1742                restr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1743                    left: restr,
1744                    op: TokenType::And,
1745                    right: pp_sub,
1746                });
1747            }
1748            if has_rel {
1749                self.advance();
1750                let rel = self.parse_relative_clause(std_var)?;
1751                restr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1752                    left: restr,
1753                    op: TokenType::And,
1754                    right: rel,
1755                });
1756            }
1757            let relation = build_constraint(self, Term::Variable(std_var));
1758            let body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1759                left: restr,
1760                op: TokenType::And,
1761                right: relation,
1762            });
1763            let quantified = self.ctx.exprs.alloc(LogicExpr::Quantifier {
1764                kind: QuantifierKind::Existential,
1765                variable: std_var,
1766                body,
1767                island_id: self.current_island,
1768            });
1769            self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1770                left: event,
1771                op: TokenType::And,
1772                right: quantified,
1773            })
1774        } else {
1775            let relation = build_constraint(self, Term::Constant(std_np.noun));
1776            self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1777                left: event,
1778                op: TokenType::And,
1779                right: relation,
1780            })
1781        };
1782        Ok(Some(result))
1783    }
1784
1785    fn parse_predicate_impl(
1786        &mut self,
1787        subject_symbol: Symbol,
1788        as_variable: bool,
1789    ) -> ParseResult<&'a LogicExpr<'a>> {
1790        let subject_term = if as_variable {
1791            Term::Variable(subject_symbol)
1792        } else {
1793            Term::Constant(subject_symbol)
1794        };
1795
1796        // Weather verb + expletive "it" detection: "it rains" → ∃e(Rain(e))
1797        let subject_str = self.interner.resolve(subject_symbol).to_lowercase();
1798        if subject_str == "it" && self.check_verb() {
1799            if let TokenType::Verb { lemma, time, .. } = &self.peek().kind {
1800                let lemma_str = self.interner.resolve(*lemma);
1801                if Lexer::is_weather_verb(lemma_str) {
1802                    let verb = *lemma;
1803                    let verb_time = *time;
1804                    self.advance(); // consume the weather verb
1805
1806                    let event_var = self.get_event_var();
1807                    let suppress_existential = self.drs.in_conditional_antecedent();
1808                    if suppress_existential {
1809                        let event_class = self.interner.intern("Event");
1810                        self.drs.introduce_event_referent(event_var, event_class);
1811                    }
1812                    let neo_event =
1813                        self.ctx
1814                            .exprs
1815                            .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
1816                                event_var,
1817                                verb,
1818                                roles: self.ctx.roles.alloc_slice(vec![]), // No thematic roles
1819                                modifiers: self.ctx.syms.alloc_slice(vec![]),
1820                                suppress_existential,
1821                                world: None,
1822                            })));
1823
1824                    return Ok(match verb_time {
1825                        Time::Past => self.ctx.exprs.alloc(LogicExpr::Temporal {
1826                            operator: TemporalOperator::Past,
1827                            body: neo_event,
1828                        }),
1829                        Time::Future => self.ctx.exprs.alloc(LogicExpr::Temporal {
1830                            operator: TemporalOperator::Future,
1831                            body: neo_event,
1832                        }),
1833                        _ => neo_event,
1834                    });
1835                }
1836            }
1837        }
1838
1839        // Weather adjective + expletive "it" detection: "it is wet" → Wet
1840        // Also handle "it's wet" where 's is Possessive token
1841        if subject_str == "it"
1842            && (self.check(&TokenType::Is)
1843                || self.check(&TokenType::Was)
1844                || self.check(&TokenType::Possessive))
1845        {
1846            let saved_pos = self.backtrack_point();
1847            self.advance(); // consume copula
1848
1849            if self.check_content_word() {
1850                let adj_lexeme = self.peek().lexeme;
1851                let adj_str = self.interner.resolve(adj_lexeme).to_lowercase();
1852
1853                if let Some(meta) = crate::lexicon::lookup_adjective_db(&adj_str) {
1854                    if meta.features.contains(&crate::lexicon::Feature::Weather) {
1855                        let adj_sym = self.consume_content_word().unwrap_or(adj_lexeme);
1856                        // Atmospheric predicate: "it is wet" → Wet
1857                        return Ok(self.ctx.exprs.alloc(LogicExpr::Predicate {
1858                            name: adj_sym,
1859                            args: self.ctx.terms.alloc_slice([]),
1860                            world: None,
1861                        }));
1862                    }
1863                }
1864            }
1865            // Not a weather adjective, restore position
1866            self.backtrack_to(&saved_pos);
1867        }
1868
1869        if self.check(&TokenType::Never) {
1870            self.advance();
1871            let verb = self.consume_verb();
1872            let verb_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
1873                name: verb,
1874                args: self.ctx.terms.alloc_slice([subject_term]),
1875                world: None,
1876            });
1877            return Ok(self.ctx.exprs.alloc(LogicExpr::UnaryOp {
1878                op: TokenType::Not,
1879                operand: verb_pred,
1880            }));
1881        }
1882
1883        if self.check_modal() {
1884            return self.parse_aspect_chain_with_term(subject_term.clone());
1885        }
1886
1887        if self.check_content_word() {
1888            let next_word = self.interner.resolve(self.peek().lexeme).to_lowercase();
1889            if next_word == "has" || next_word == "have" || next_word == "had" {
1890                // Look ahead to distinguish perfect aspect ("has eaten") from possession ("has 3 children")
1891                // Perfect aspect: has/have/had + verb
1892                // Possession: has/have/had + number/noun
1893                let is_perfect_aspect = if self.current + 1 < self.tokens.len() {
1894                    let next_token = &self.tokens[self.current + 1].kind;
1895                    matches!(next_token, TokenType::Verb { .. } | TokenType::Not)
1896                        && !matches!(next_token, TokenType::Number(_))
1897                } else {
1898                    false
1899                };
1900                if is_perfect_aspect {
1901                    return self.parse_aspect_chain(subject_symbol);
1902                }
1903                // Otherwise, treat "has" as a main verb (possession) and continue below
1904            }
1905        }
1906
1907        if self.check(&TokenType::Had) {
1908            return self.parse_aspect_chain(subject_symbol);
1909        }
1910
1911        // Handle do-support: "I do/don't know who"
1912        if self.check(&TokenType::Does) || self.check(&TokenType::Do) {
1913            self.advance();
1914            let is_negated = self.match_token(&[TokenType::Not]);
1915
1916            if self.check(&TokenType::Ever) {
1917                self.advance();
1918            }
1919
1920            if self.check_verb() {
1921                let (verb, verb_time, verb_aspect, verb_class) = self.consume_verb_with_metadata();
1922
1923                // Check for embedded wh-clause with sluicing: "I don't know who"
1924                if self.check_wh_word() {
1925                    let wh_token = self.advance().kind.clone();
1926                    let is_who = matches!(wh_token, TokenType::Who);
1927                    let is_what = matches!(wh_token, TokenType::What);
1928
1929                    let is_sluicing = self.is_at_end()
1930                        || self.check(&TokenType::Period)
1931                        || self.check(&TokenType::Comma);
1932
1933                    if is_sluicing {
1934                        if let Some(template) = self.last_event_template.clone() {
1935                            let wh_var = self.next_var_name();
1936
1937                            let roles: Vec<_> = if is_who {
1938                                std::iter::once((ThematicRole::Agent, Term::Variable(wh_var)))
1939                                    .chain(template.non_agent_roles.iter().cloned())
1940                                    .collect()
1941                            } else if is_what {
1942                                vec![
1943                                    (ThematicRole::Agent, subject_term.clone()),
1944                                    (ThematicRole::Theme, Term::Variable(wh_var)),
1945                                ]
1946                            } else {
1947                                std::iter::once((ThematicRole::Agent, Term::Variable(wh_var)))
1948                                    .chain(template.non_agent_roles.iter().cloned())
1949                                    .collect()
1950                            };
1951
1952                            let event_var = self.get_event_var();
1953                            let suppress_existential = self.drs.in_conditional_antecedent();
1954                            let reconstructed =
1955                                self.ctx
1956                                    .exprs
1957                                    .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
1958                                        event_var,
1959                                        verb: template.verb,
1960                                        roles: self.ctx.roles.alloc_slice(roles),
1961                                        modifiers: self
1962                                            .ctx
1963                                            .syms
1964                                            .alloc_slice(template.modifiers.clone()),
1965                                        suppress_existential,
1966                                        world: None,
1967                                    })));
1968
1969                            let question = self.ctx.exprs.alloc(LogicExpr::Question {
1970                                wh_variable: wh_var,
1971                                body: reconstructed,
1972                            });
1973
1974                            let know_event =
1975                                self.ctx
1976                                    .exprs
1977                                    .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
1978                                        event_var: self.get_event_var(),
1979                                        verb,
1980                                        roles: self.ctx.roles.alloc_slice(vec![
1981                                            (ThematicRole::Agent, subject_term.clone()),
1982                                            (ThematicRole::Theme, Term::Proposition(question)),
1983                                        ]),
1984                                        modifiers: self.ctx.syms.alloc_slice(vec![]),
1985                                        suppress_existential,
1986                                        world: None,
1987                                    })));
1988
1989                            let result = if is_negated {
1990                                self.ctx.exprs.alloc(LogicExpr::UnaryOp {
1991                                    op: TokenType::Not,
1992                                    operand: know_event,
1993                                })
1994                            } else {
1995                                know_event
1996                            };
1997
1998                            return Ok(result);
1999                        }
2000                    }
2001                }
2002
2003                // Regular do-support ("does/do/don't VERB …"): delegate the whole
2004                // VP — object, measure phrase, PPs, aspect — to the shared builder
2005                // so every complement form folds exactly as in the positive path,
2006                // wrapping in ¬ when "not"/"never" was present. The negative scope
2007                // is open across the complement so NPIs inside it are licensed.
2008                if is_negated {
2009                    self.negative_depth += 1;
2010                }
2011                let vp = self.build_verb_vp(
2012                    subject_symbol,
2013                    subject_term,
2014                    as_variable,
2015                    verb,
2016                    verb_time,
2017                    verb_aspect,
2018                    verb_class,
2019                )?;
2020                if is_negated {
2021                    self.negative_depth -= 1;
2022                    return Ok(self.ctx.exprs.alloc(LogicExpr::UnaryOp {
2023                        op: TokenType::Not,
2024                        operand: vp,
2025                    }));
2026                }
2027                return Ok(vp);
2028            }
2029        }
2030
2031        // Check for auxiliary (like "did" in "did not bark")
2032        // BUT: "did it" should be parsed as verb "do" with object "it"
2033        // We lookahead to check if this is truly an auxiliary usage
2034        if self.check_auxiliary() && self.is_true_auxiliary_usage() {
2035            let aux_time = if let TokenType::Auxiliary(time) = self.advance().kind {
2036                time
2037            } else {
2038                Time::None
2039            };
2040            self.pending_time = Some(aux_time);
2041
2042            if self.match_token(&[TokenType::Not]) {
2043                self.negative_depth += 1;
2044
2045                // A bare verb the lexicon ALSO lists as a performative ("didn't ORDER",
2046                // "didn't CALL") is the clause's main verb after do-support, not a
2047                // speech act — re-tag it so check_verb consumes it (the tense comes from
2048                // the "did"/"does" auxiliary).
2049                if let TokenType::Performative(_) = self.peek().kind {
2050                    let lemma = self
2051                        .interner
2052                        .intern(&self.interner.resolve(self.peek().lexeme).to_lowercase());
2053                    self.tokens[self.current].kind = TokenType::Verb {
2054                        lemma,
2055                        time: Time::None,
2056                        aspect: Aspect::Simple,
2057                        class: crate::lexicon::VerbClass::Activity,
2058                    };
2059                }
2060                // Check for verb or "do" (TokenType::Do is separate from TokenType::Verb)
2061                if self.check_verb() || self.check(&TokenType::Do) {
2062                    let (verb, verb_time, verb_aspect, verb_class) = if self.check(&TokenType::Do) {
2063                        self.advance(); // consume "do"
2064                        (
2065                            self.interner.intern("Do"),
2066                            Time::None,
2067                            Aspect::Simple,
2068                            crate::lexicon::VerbClass::Activity,
2069                        )
2070                    } else {
2071                        self.consume_verb_with_metadata()
2072                    };
2073
2074                    if self.check_quantifier() {
2075                        let quantifier_token = self.advance().kind.clone();
2076                        let object_np = self.parse_noun_phrase(false)?;
2077                        let obj_var = self.next_var_name();
2078
2079                        let obj_restriction = self.ctx.exprs.alloc(LogicExpr::Predicate {
2080                            name: object_np.noun,
2081                            args: self.ctx.terms.alloc_slice([Term::Variable(obj_var)]),
2082                            world: None,
2083                        });
2084
2085                        let verb_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
2086                            name: verb,
2087                            args: self
2088                                .ctx
2089                                .terms
2090                                .alloc_slice([subject_term, Term::Variable(obj_var)]),
2091                            world: None,
2092                        });
2093
2094                        let quantified = self.quantify_argument(
2095                            &quantifier_token,
2096                            obj_var,
2097                            obj_restriction,
2098                            verb_pred,
2099                        );
2100
2101                        let effective_time = self.pending_time.take().unwrap_or(Time::None);
2102                        let with_time = match effective_time {
2103                            Time::Past => self.ctx.exprs.alloc(LogicExpr::Temporal {
2104                                operator: TemporalOperator::Past,
2105                                body: quantified,
2106                            }),
2107                            Time::Future => self.ctx.exprs.alloc(LogicExpr::Temporal {
2108                                operator: TemporalOperator::Future,
2109                                body: quantified,
2110                            }),
2111                            _ => quantified,
2112                        };
2113
2114                        self.negative_depth -= 1;
2115                        return Ok(self.ctx.exprs.alloc(LogicExpr::UnaryOp {
2116                            op: TokenType::Not,
2117                            operand: with_time,
2118                        }));
2119                    }
2120
2121                    if self.check_npi_object() {
2122                        let npi_token = self.advance().kind.clone();
2123                        let obj_var = self.next_var_name();
2124
2125                        let restriction_name = match npi_token {
2126                            TokenType::Anything => "Thing",
2127                            TokenType::Anyone => "Person",
2128                            _ => "Thing",
2129                        };
2130
2131                        let restriction_sym = self.interner.intern(restriction_name);
2132                        let obj_restriction = self.ctx.exprs.alloc(LogicExpr::Predicate {
2133                            name: restriction_sym,
2134                            args: self.ctx.terms.alloc_slice([Term::Variable(obj_var)]),
2135                            world: None,
2136                        });
2137
2138                        let verb_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
2139                            name: verb,
2140                            args: self
2141                                .ctx
2142                                .terms
2143                                .alloc_slice([subject_term, Term::Variable(obj_var)]),
2144                            world: None,
2145                        });
2146
2147                        let body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2148                            left: obj_restriction,
2149                            op: TokenType::And,
2150                            right: verb_pred,
2151                        });
2152
2153                        let quantified = self.ctx.exprs.alloc(LogicExpr::Quantifier {
2154                            kind: QuantifierKind::Existential,
2155                            variable: obj_var,
2156                            body,
2157                            island_id: self.current_island,
2158                        });
2159
2160                        let effective_time = self.pending_time.take().unwrap_or(Time::None);
2161                        let with_time = match effective_time {
2162                            Time::Past => self.ctx.exprs.alloc(LogicExpr::Temporal {
2163                                operator: TemporalOperator::Past,
2164                                body: quantified,
2165                            }),
2166                            Time::Future => self.ctx.exprs.alloc(LogicExpr::Temporal {
2167                                operator: TemporalOperator::Future,
2168                                body: quantified,
2169                            }),
2170                            _ => quantified,
2171                        };
2172
2173                        self.negative_depth -= 1;
2174                        return Ok(self.ctx.exprs.alloc(LogicExpr::UnaryOp {
2175                            op: TokenType::Not,
2176                            operand: with_time,
2177                        }));
2178                    }
2179
2180                    // Delegate the VP complement (object/measure/PP/aspect) to the
2181                    // shared builder so negated do-support folds every complement
2182                    // form exactly as the positive path does. pending_time still
2183                    // carries the auxiliary's tense ("did" → Past) into the build.
2184                    let vp = self.build_verb_vp(
2185                        subject_symbol,
2186                        subject_term,
2187                        as_variable,
2188                        verb,
2189                        verb_time,
2190                        verb_aspect,
2191                        verb_class,
2192                    )?;
2193
2194                    self.negative_depth -= 1;
2195                    return Ok(self.ctx.exprs.alloc(LogicExpr::UnaryOp {
2196                        op: TokenType::Not,
2197                        operand: vp,
2198                    }));
2199                }
2200
2201                self.negative_depth -= 1;
2202            }
2203        }
2204
2205        if self.check(&TokenType::Is)
2206            || self.check(&TokenType::Are)
2207            || self.check(&TokenType::Was)
2208            || self.check(&TokenType::Were)
2209        {
2210            let copula_time = if self.check(&TokenType::Was) || self.check(&TokenType::Were) {
2211                Time::Past
2212            } else {
2213                Time::Present
2214            };
2215            self.advance();
2216
2217            // Check for negation: "was not caught", "is not happy"
2218            let is_negated = self.check(&TokenType::Not);
2219            if is_negated {
2220                self.advance(); // consume "not"
2221            }
2222
2223            // Check for temporal adverbs after copula: "is eventually Y", "is always Y", "is never Y"
2224            let mut copula_temporal: Option<super::CopulaTemporal> = None;
2225            if !is_negated {
2226                if self.check(&TokenType::Never) {
2227                    self.advance();
2228                    copula_temporal = Some(super::CopulaTemporal::Never);
2229                } else if let TokenType::Adverb(sym)
2230                | TokenType::ScopalAdverb(sym)
2231                | TokenType::TemporalAdverb(sym) = &self.peek().kind
2232                {
2233                    let resolved = self.interner.resolve(*sym).to_string();
2234                    if resolved == "Always" || resolved == "always" {
2235                        self.advance();
2236                        copula_temporal = Some(super::CopulaTemporal::Always);
2237                    } else if resolved == "Eventually" || resolved == "eventually" {
2238                        self.advance();
2239                        copula_temporal = Some(super::CopulaTemporal::Eventually);
2240                    }
2241                }
2242            }
2243
2244            if self.check_verb() {
2245                let (verb, _verb_time, verb_aspect, verb_class) = self.consume_verb_with_metadata();
2246
2247                // Stative verbs cannot be progressive
2248                if verb_class.is_stative() && verb_aspect == Aspect::Progressive {
2249                    return Err(crate::error::ParseError {
2250                        kind: crate::error::ParseErrorKind::StativeProgressiveConflict,
2251                        span: self.current_span(),
2252                    });
2253                }
2254
2255                let mut predicate: &'a LogicExpr<'a> = self.ctx.exprs.alloc(LogicExpr::Predicate {
2256                    name: verb,
2257                    args: self.ctx.terms.alloc_slice([subject_term]),
2258                    world: None,
2259                });
2260
2261                // Passive by-phrase: the NP after `by` is the AGENT and must fill
2262                // the predicate's agent (FIRST) slot — `See(Mary, John)` for
2263                // "John was seen by Mary" — matching the main passive path. Handle
2264                // it BEFORE the generic locative-PP loop below, which would
2265                // otherwise demote the agent into a spurious `by(theme, agent)`.
2266                if self.check_by_preposition() {
2267                    self.advance(); // consume "by"
2268                    if self.check_content_word()
2269                        || matches!(self.peek().kind, TokenType::Article(_))
2270                    {
2271                        let agent = self.parse_noun_phrase(true)?;
2272                        // A DESCRIPTIVE by-agent becomes its own restrictor-carrying
2273                        // entity scoping the relation; a bare one keeps the constant.
2274                        let (agent_term, agent_restr) = self.possessor_entity(&agent);
2275                        let core = self.ctx.exprs.alloc(LogicExpr::Predicate {
2276                            name: verb,
2277                            args: self.ctx.terms.alloc_slice([agent_term, subject_term]),
2278                            world: None,
2279                        });
2280                        predicate = self.wrap_in_possessor_entity(agent_restr, core);
2281                    }
2282                }
2283
2284                // Trailing PP adjuncts on the passive participle ("was found in
2285                // Spain", "was taken on May 12", "was at 88.2 W") and a calendar-unit
2286                // offset ("was taken 1 month after Y") — predicated of the theme.
2287                // This makes the embedded VP parser (of-pair members, delegated
2288                // relative clauses) as capable as parse_atom's main passive path.
2289                while self.check_preposition()
2290                    && !self.check_of_preposition()
2291                    && !self.pp_is_cycle_temporal()
2292                {
2293                    let prep = match self.advance().kind {
2294                        TokenType::Preposition(s) => s,
2295                        _ => break,
2296                    };
2297                    let adjunct = if self.check_number() {
2298                        let m = self.parse_measure_phrase()?;
2299                        self.ctx.exprs.alloc(LogicExpr::Predicate {
2300                            name: prep,
2301                            args: self.ctx.terms.alloc_slice([subject_term, *m]),
2302                            world: None,
2303                        })
2304                    } else if self.check_content_word()
2305                        || matches!(self.peek().kind, TokenType::Article(_))
2306                    {
2307                        let obj = self.parse_noun_phrase(true)?;
2308                        self.ctx.exprs.alloc(LogicExpr::Predicate {
2309                            name: prep,
2310                            args: self
2311                                .ctx
2312                                .terms
2313                                .alloc_slice([subject_term, Term::Constant(obj.noun)]),
2314                            world: None,
2315                        })
2316                    } else {
2317                        break;
2318                    };
2319                    predicate = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2320                        left: predicate,
2321                        op: TokenType::And,
2322                        right: adjunct,
2323                    });
2324                }
2325                if let Some(constraint) = self.parse_temporal_offset_constraint(subject_term)? {
2326                    predicate = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2327                        left: predicate,
2328                        op: TokenType::And,
2329                        right: constraint,
2330                    });
2331                }
2332
2333                let with_aspect = if verb_aspect == Aspect::Progressive {
2334                    // Semelfactive + Progressive → Iterative
2335                    let operator = if verb_class == crate::lexicon::VerbClass::Semelfactive {
2336                        AspectOperator::Iterative
2337                    } else {
2338                        AspectOperator::Progressive
2339                    };
2340                    self.ctx.exprs.alloc(LogicExpr::Aspectual {
2341                        operator,
2342                        body: predicate,
2343                    })
2344                } else {
2345                    predicate
2346                };
2347
2348                let with_time = if copula_time == Time::Past {
2349                    self.ctx.exprs.alloc(LogicExpr::Temporal {
2350                        operator: TemporalOperator::Past,
2351                        body: with_aspect,
2352                    })
2353                } else {
2354                    with_aspect
2355                };
2356
2357                let with_neg = if is_negated {
2358                    self.ctx.exprs.alloc(LogicExpr::UnaryOp {
2359                        op: TokenType::Not,
2360                        operand: with_time,
2361                    })
2362                } else {
2363                    with_time
2364                };
2365
2366                let result = match copula_temporal {
2367                    Some(super::CopulaTemporal::Always) => {
2368                        self.ctx.exprs.alloc(LogicExpr::Temporal {
2369                            operator: TemporalOperator::Always,
2370                            body: with_neg,
2371                        })
2372                    }
2373                    Some(super::CopulaTemporal::Never) => {
2374                        let negated = self.ctx.exprs.alloc(LogicExpr::UnaryOp {
2375                            op: TokenType::Not,
2376                            operand: with_time,
2377                        });
2378                        self.ctx.exprs.alloc(LogicExpr::Temporal {
2379                            operator: TemporalOperator::Always,
2380                            body: negated,
2381                        })
2382                    }
2383                    Some(super::CopulaTemporal::Eventually) => {
2384                        self.ctx.exprs.alloc(LogicExpr::Temporal {
2385                            operator: TemporalOperator::Eventually,
2386                            body: with_neg,
2387                        })
2388                    }
2389                    None => with_neg,
2390                };
2391
2392                return Ok(result);
2393            }
2394
2395            // "is 14 inches tall" / "is 5 meters long" — a measure phrase + a
2396            // dimensional adjective: Adj(subject, measure). Also bare "is 98.6
2397            // degrees" → Identity. parse_atom handles this for its subjects; the
2398            // of-pair / quantified-subject copula VPs ("the other is 14 inches
2399            // tall") reach here. A measure-OFFSET comparative ("is 2 inches
2400            // taller than X") is left to fall through (not mis-read as Identity).
2401            if self.check_number() {
2402                let after_measure_is_comparative = {
2403                    let mut i = self.current + 1; // past the number
2404                    if matches!(
2405                        self.tokens.get(i).map(|t| &t.kind),
2406                        Some(TokenType::Noun(_)) | Some(TokenType::CalendarUnit(_))
2407                    ) {
2408                        i += 1; // past an optional unit word
2409                    }
2410                    matches!(
2411                        self.tokens.get(i).map(|t| &t.kind),
2412                        Some(TokenType::Comparative(_))
2413                    )
2414                };
2415                if !after_measure_is_comparative {
2416                    let measure = self.parse_measure_phrase()?;
2417                    let pred = if self.check_content_word() {
2418                        let adj = self.consume_content_word()?;
2419                        self.ctx.exprs.alloc(LogicExpr::Predicate {
2420                            name: adj,
2421                            args: self.ctx.terms.alloc_slice([subject_term, *measure]),
2422                            world: None,
2423                        })
2424                    } else {
2425                        self.ctx.exprs.alloc(LogicExpr::Identity {
2426                            left: self.ctx.terms.alloc(subject_term),
2427                            right: measure,
2428                        })
2429                    };
2430                    return Ok(self.finish_copula(pred, copula_time, is_negated, copula_temporal));
2431                }
2432            }
2433
2434            // "is on Rosewood Street" / "is from Australia" — locative/origin PP in copula position.
2435            // Excludes "by" which is handled as passive-agent above.
2436            if self.check_preposition() && !self.check_by_preposition() {
2437                let prep_token = self.advance().clone();
2438                let prep_sym = match prep_token.kind {
2439                    TokenType::Preposition(s) => s,
2440                    _ => unreachable!("guarded by check_preposition()"),
2441                };
2442                // A coordinate / measure object ("is at 88.2 W", "is at 40.5 N")
2443                // routes through parse_measure_phrase, which takes the trailing
2444                // direction/unit; otherwise a plain NP object.
2445                let base = if self.check_number() {
2446                    let m = self.parse_measure_phrase()?;
2447                    self.ctx.exprs.alloc(LogicExpr::Predicate {
2448                        name: prep_sym,
2449                        args: self.ctx.terms.alloc_slice([subject_term, *m]),
2450                        world: None,
2451                    })
2452                } else {
2453                    let pp_obj = self.parse_noun_phrase(true)?;
2454                    self.ctx.exprs.alloc(LogicExpr::Predicate {
2455                        name: prep_sym,
2456                        args: self
2457                            .ctx
2458                            .terms
2459                            .alloc_slice([subject_term, Term::Constant(pp_obj.noun)]),
2460                        world: None,
2461                    })
2462                };
2463                let with_time = if copula_time == Time::Past {
2464                    self.ctx.exprs.alloc(LogicExpr::Temporal {
2465                        operator: TemporalOperator::Past,
2466                        body: base,
2467                    })
2468                } else {
2469                    base
2470                };
2471                return Ok(if is_negated {
2472                    self.ctx.exprs.alloc(LogicExpr::UnaryOp {
2473                        op: TokenType::Not,
2474                        operand: with_time,
2475                    })
2476                } else {
2477                    with_time
2478                });
2479            }
2480
2481            // "is Tara" — identity with a proper name (X = Tara), enabling Leibniz's
2482            // Law. But "is Kerry's project" is a POSSESSIVE NP complement
2483            // (Project(x) ∧ Possesses(Kerry, x)), so a following "'s" diverts to NP
2484            // predication instead of the bare identity.
2485            if let TokenType::ProperName(pname) = self.peek().kind {
2486                if matches!(
2487                    self.tokens.get(self.current + 1).map(|t| &t.kind),
2488                    Some(TokenType::Possessive)
2489                ) {
2490                    // "is Ginger's." — an ELIDED possessed noun (a clause boundary
2491                    // follows "'s") → Possesses(Ginger, subject). parse_atom's
2492                    // copula handles this; the of-pair / quantified-subject VPs
2493                    // route here, where it previously failed (ExpectedContentWord
2494                    // at the period). "is Ginger's PROJECT" still parses the full
2495                    // possessive NP below.
2496                    let elided = matches!(
2497                        self.tokens.get(self.current + 2).map(|t| &t.kind),
2498                        Some(TokenType::Period)
2499                            | Some(TokenType::EOF)
2500                            | Some(TokenType::Comma)
2501                            | Some(TokenType::And)
2502                            | Some(TokenType::Or)
2503                            | None
2504                    );
2505                    if elided {
2506                        self.advance(); // proper name
2507                        self.advance(); // possessive
2508                        let pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
2509                            name: self.interner.intern("Possesses"),
2510                            args: self
2511                                .ctx
2512                                .terms
2513                                .alloc_slice([Term::Constant(pname), subject_term]),
2514                            world: None,
2515                        });
2516                        return Ok(self.finish_copula(
2517                            pred,
2518                            copula_time,
2519                            is_negated,
2520                            copula_temporal,
2521                        ));
2522                    }
2523                    let saved_ctx = self.nominal_np_context;
2524                    self.nominal_np_context = true;
2525                    let np_result = self.parse_noun_phrase(true);
2526                    self.nominal_np_context = saved_ctx;
2527                    let np = np_result?;
2528                    let pred = self.nominal_predication_with_pps(subject_term, &np);
2529                    return Ok(self.finish_copula(pred, copula_time, is_negated, copula_temporal));
2530                }
2531
2532                // A possessive after a MULTI-WORD proper name ("is Tim Tucker's
2533                // film") — the single-word check above misses it (the second name
2534                // sits where the "'s" would be). Absorb the full possessor, then
2535                // predicate the possessed noun: Possesses(Tim_Tucker, x) ∧ Film(x).
2536                let multiword_poss = {
2537                    let mut k = self.current + 1;
2538                    while matches!(
2539                        self.tokens.get(k).map(|t| &t.kind),
2540                        Some(TokenType::ProperName(_))
2541                    ) {
2542                        k += 1;
2543                    }
2544                    if k > self.current + 1
2545                        && matches!(
2546                            self.tokens.get(k).map(|t| &t.kind),
2547                            Some(TokenType::Possessive)
2548                        )
2549                    {
2550                        Some(k)
2551                    } else {
2552                        None
2553                    }
2554                };
2555                if let Some(poss_pos) = multiword_poss {
2556                    let elided = matches!(
2557                        self.tokens.get(poss_pos + 1).map(|t| &t.kind),
2558                        Some(TokenType::Period)
2559                            | Some(TokenType::EOF)
2560                            | Some(TokenType::Comma)
2561                            | Some(TokenType::And)
2562                            | Some(TokenType::Or)
2563                            | None
2564                    );
2565                    self.advance(); // first proper name
2566                    let possessor = self.absorb_multiword_proper_name(pname);
2567                    self.advance(); // possessive
2568                    let poss_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
2569                        name: self.interner.intern("Possesses"),
2570                        args: self
2571                            .ctx
2572                            .terms
2573                            .alloc_slice([Term::Constant(possessor), subject_term]),
2574                        world: None,
2575                    });
2576                    let pred = if elided {
2577                        poss_pred
2578                    } else {
2579                        let saved_ctx = self.nominal_np_context;
2580                        self.nominal_np_context = true;
2581                        let np_result = self.parse_noun_phrase(true);
2582                        self.nominal_np_context = saved_ctx;
2583                        let np = np_result?;
2584                        let np_pred = self.nominal_predication_with_pps(subject_term, &np);
2585                        self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2586                            left: np_pred,
2587                            op: TokenType::And,
2588                            right: poss_pred,
2589                        })
2590                    };
2591                    return Ok(self.finish_copula(pred, copula_time, is_negated, copula_temporal));
2592                }
2593
2594                self.advance();
2595                // Absorb subsequent capitalized words into one multi-word proper
2596                // name ("Porcher Place", "Highland Drive") — a place/title name is
2597                // a single entity, so the identity must not strand the second word.
2598                let pname = self.absorb_multiword_proper_name(pname);
2599                let identity = self.ctx.exprs.alloc(LogicExpr::Identity {
2600                    left: self.ctx.terms.alloc(subject_term),
2601                    right: self.ctx.terms.alloc(Term::Constant(pname)),
2602                });
2603                return Ok(self.finish_copula(identity, copula_time, is_negated, copula_temporal));
2604            }
2605
2606            // "is either A or B" — disjunctive predication: A(x) ∨ B(x).
2607            if self.check(&TokenType::Either) {
2608                self.advance(); // consume "either"
2609                let saved_ctx = self.nominal_np_context;
2610                self.nominal_np_context = true;
2611                let np1_result = self.parse_noun_phrase(true);
2612                self.nominal_np_context = saved_ctx;
2613                let np1 = np1_result?;
2614                // Keep the disjunct's PP restrictors ("either the vegetables FROM
2615                // JESUP or …") — bare nominal_predication drops them, the same
2616                // meaning-loss the plain copula complement avoids with _with_pps.
2617                let pred1 = self.nominal_predication_with_pps(subject_term, &np1);
2618                // A relative clause on the disjunct ("either the one WHO won or …")
2619                // attaches before "or"; the second disjunct's after np2.
2620                let pred1 = self.conjoin_trailing_relative(pred1, subject_term)?;
2621                if self.check(&TokenType::Or) {
2622                    self.advance(); // consume "or"
2623                    let saved_ctx2 = self.nominal_np_context;
2624                    self.nominal_np_context = true;
2625                    let np2_result = self.parse_noun_phrase(true);
2626                    self.nominal_np_context = saved_ctx2;
2627                    let np2 = np2_result?;
2628                    let pred2 = self.nominal_predication_with_pps(subject_term, &np2);
2629                    let pred2 = self.conjoin_trailing_relative(pred2, subject_term)?;
2630                    let disj = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2631                        left: pred1,
2632                        op: TokenType::Or,
2633                        right: pred2,
2634                    });
2635                    return Ok(self.finish_copula(disj, copula_time, is_negated, copula_temporal));
2636                }
2637                return Ok(self.finish_copula(pred1, copula_time, is_negated, copula_temporal));
2638            }
2639
2640            // "is the mansion" / "is the frat on Holly Street" / "is the Alvarado
2641            // family's house" — NP predication keeping the genitive AND the
2642            // predicate NP's PP restrictors ("on Holly Street"); dropping the PP
2643            // is a meaning-loss parse.
2644            if self.check_article() {
2645                let saved_ctx = self.nominal_np_context;
2646                self.nominal_np_context = true;
2647                let pred_np_result = self.parse_noun_phrase(true);
2648                self.nominal_np_context = saved_ctx;
2649                let pred_np = pred_np_result?;
2650                let pred = self.nominal_predication_with_pps(subject_term, &pred_np);
2651                // A relative clause on the predicate nominal ("was the player WHO
2652                // played", "is the one THAT won") is predicated of the subject —
2653                // being that player entails the subject played. neither/nor and
2654                // quantified subjects route their copula complement through here.
2655                let pred = self.conjoin_trailing_relative(pred, subject_term)?;
2656                return Ok(self.finish_copula(pred, copula_time, is_negated, copula_temporal));
2657            }
2658
2659            // "is older" / "is faster than the cobra" — a comparative copula
2660            // complement. parse_atom routes its subjects to parse_comparative;
2661            // quantified / of-pair subjects (parse_predicate_with_subject) reach
2662            // here, so the comparative must be handled too. Use the COMPARATIVE
2663            // surface ("older" → Older), not the base lemma, so the degree
2664            // survives. Bare (no "than") → unary property ("one is older"); with
2665            // "than" → binary comparison.
2666            if let TokenType::Comparative(_) = self.peek().kind {
2667                let comp_tok = self.advance().clone();
2668                let comp_surface = self.interner.resolve(comp_tok.lexeme).to_string();
2669                let comp_name = {
2670                    let mut c = comp_surface.chars();
2671                    match c.next() {
2672                        Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
2673                        None => comp_surface.clone(),
2674                    }
2675                };
2676                let name = self.interner.intern(&comp_name);
2677                let pred = if self.check(&TokenType::Than) {
2678                    self.advance(); // than
2679                    let std_np = self.parse_noun_phrase(true)?;
2680                    let std = self.nominal_predication(Term::Constant(std_np.noun), &std_np);
2681                    let cmp = self.ctx.exprs.alloc(LogicExpr::Predicate {
2682                        name,
2683                        args: self
2684                            .ctx
2685                            .terms
2686                            .alloc_slice([subject_term, Term::Constant(std_np.noun)]),
2687                        world: None,
2688                    });
2689                    // Keep the standard's own restrictors (a bare proper name's
2690                    // std is vacuous Predicate, harmless).
2691                    if matches!(std, LogicExpr::Predicate { args, .. } if args.len() == 1) {
2692                        cmp
2693                    } else {
2694                        self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2695                            left: cmp,
2696                            op: TokenType::And,
2697                            right: std,
2698                        })
2699                    }
2700                } else {
2701                    self.ctx.exprs.alloc(LogicExpr::Predicate {
2702                        name,
2703                        args: self.ctx.terms.alloc_slice([subject_term]),
2704                        world: None,
2705                    })
2706                };
2707                return Ok(self.finish_copula(pred, copula_time, is_negated, copula_temporal));
2708            }
2709
2710            // Copula complement led by a temporal/ordinal adverb: "was FIRST", "is
2711            // NOW the leader". Shared with parse_atom's copula path.
2712            if let Some(base) = self.copula_temporal_adverb_complement(subject_term.clone())? {
2713                return Ok(self.finish_copula(base, copula_time, is_negated, copula_temporal));
2714            }
2715
2716            let predicate = self.consume_content_word()?;
2717
2718            // Coordinated predicate adjectives — "is black and red" (or "black &
2719            // red", where "&" lexes to "and") → Adj1(subj) ∧ Adj2(subj). Mirrors
2720            // parse_atom; of-pair / neither / quantified subjects reach this shared
2721            // VP parser. Requires "and" before each extra adjective.
2722            {
2723                let mut coord_adjs: Vec<Symbol> = vec![predicate];
2724                while self.check(&TokenType::And) {
2725                    let saved = self.backtrack_point();
2726                    self.advance();
2727                    if let TokenType::Adjective(a) = self.peek().kind {
2728                        // "and ADJ is/are/verb …" — ADJ is the SUBJECT of a new
2729                        // clause, not a coordinated predicate adjective.
2730                        if matches!(
2731                            self.tokens.get(self.current + 1).map(|t| &t.kind),
2732                            Some(TokenType::Is)
2733                                | Some(TokenType::Are)
2734                                | Some(TokenType::Was)
2735                                | Some(TokenType::Were)
2736                                | Some(TokenType::Verb { .. })
2737                        ) {
2738                            self.backtrack_to(&saved);
2739                            break;
2740                        }
2741                        self.advance();
2742                        coord_adjs.push(a);
2743                    } else {
2744                        self.backtrack_to(&saved);
2745                        break;
2746                    }
2747                }
2748                if coord_adjs.len() > 1 {
2749                    let mut conj: &'a LogicExpr<'a> = self.ctx.exprs.alloc(LogicExpr::Predicate {
2750                        name: coord_adjs[0],
2751                        args: self.ctx.terms.alloc_slice([subject_term.clone()]),
2752                        world: None,
2753                    });
2754                    for &a in &coord_adjs[1..] {
2755                        let p = self.ctx.exprs.alloc(LogicExpr::Predicate {
2756                            name: a,
2757                            args: self.ctx.terms.alloc_slice([subject_term.clone()]),
2758                            world: None,
2759                        });
2760                        conj = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2761                            left: conj,
2762                            op: TokenType::And,
2763                            right: p,
2764                        });
2765                    }
2766                    return Ok(self.finish_copula(conj, copula_time, is_negated, copula_temporal));
2767                }
2768            }
2769
2770            // Postposed measure complement on a predicate adjective — "is worth
2771            // $26 billion", "is worth 5 dollars" → Worth(subject, $26 billion).
2772            // Mirrors parse_atom's copula path; of-pair / neither / quantified
2773            // subjects reach this shared VP parser, so the complement lives here
2774            // too. A number after a predicate adjective is never a separate clause.
2775            if self.check_number() {
2776                let measure = self.parse_measure_phrase()?;
2777                let pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
2778                    name: predicate,
2779                    args: self.ctx.terms.alloc_slice([subject_term.clone(), *measure]),
2780                    world: None,
2781                });
2782                return Ok(self.finish_copula(pred, copula_time, is_negated, copula_temporal));
2783            }
2784
2785            let base_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
2786                name: predicate,
2787                args: self.ctx.terms.alloc_slice([subject_term]),
2788                world: None,
2789            });
2790
2791            let with_time = if copula_time == Time::Past {
2792                self.ctx.exprs.alloc(LogicExpr::Temporal {
2793                    operator: TemporalOperator::Past,
2794                    body: base_pred,
2795                })
2796            } else {
2797                base_pred
2798            };
2799
2800            let with_neg = if is_negated {
2801                self.ctx.exprs.alloc(LogicExpr::UnaryOp {
2802                    op: TokenType::Not,
2803                    operand: with_time,
2804                })
2805            } else {
2806                with_time
2807            };
2808
2809            let result = match copula_temporal {
2810                Some(super::CopulaTemporal::Always) => self.ctx.exprs.alloc(LogicExpr::Temporal {
2811                    operator: TemporalOperator::Always,
2812                    body: with_neg,
2813                }),
2814                Some(super::CopulaTemporal::Never) => {
2815                    let negated = self.ctx.exprs.alloc(LogicExpr::UnaryOp {
2816                        op: TokenType::Not,
2817                        operand: with_time,
2818                    });
2819                    self.ctx.exprs.alloc(LogicExpr::Temporal {
2820                        operator: TemporalOperator::Always,
2821                        body: negated,
2822                    })
2823                }
2824                Some(super::CopulaTemporal::Eventually) => {
2825                    self.ctx.exprs.alloc(LogicExpr::Temporal {
2826                        operator: TemporalOperator::Eventually,
2827                        body: with_neg,
2828                    })
2829                }
2830                None => with_neg,
2831            };
2832
2833            return Ok(result);
2834        }
2835
2836        // Handle "did it" - when Auxiliary(Past) is used as a transitive verb (past of "do")
2837        // This happens when we bypassed auxiliary handling because of lookahead
2838        if self.check_auxiliary_as_main_verb() {
2839            return self.parse_do_as_main_verb(subject_term);
2840        }
2841
2842        self.parse_finite_verb_vp(subject_symbol, subject_term, as_variable)
2843    }
2844
2845    /// Parses a finite verb's VP body: the verb, its object/measure/coordinated/
2846    /// ditransitive complement, trailing PPs, object-internal adjectives/PPs, and
2847    /// aspectual operators — building the NeoEvent. Shared by the positive predicate
2848    /// path and the do-support paths ("does/do/did not VERB …"), which wrap the
2849    /// result in negation; unifying them so every complement form folds uniformly.
2850    pub(super) fn parse_finite_verb_vp(
2851        &mut self,
2852        subject_symbol: Symbol,
2853        subject_term: Term<'a>,
2854        as_variable: bool,
2855    ) -> ParseResult<&'a LogicExpr<'a>> {
2856        if self.check_verb() {
2857            let (verb, verb_time, verb_aspect, verb_class) = self.consume_verb_with_metadata();
2858            self.build_verb_vp(
2859                subject_symbol,
2860                subject_term,
2861                as_variable,
2862                verb,
2863                verb_time,
2864                verb_aspect,
2865                verb_class,
2866            )
2867        } else {
2868            Ok(self.ctx.exprs.alloc(LogicExpr::Atom(subject_symbol)))
2869        }
2870    }
2871
2872    /// The VP body shared by the positive predicate path and the do-support paths
2873    /// ("does/do/did not VERB …"): the object/measure/coordinated/ditransitive
2874    /// complement, trailing PPs, object-internal adjectives/PPs, and aspectual
2875    /// operators — building and returning the NeoEvent. The caller consumes the
2876    /// verb (with metadata); negated do-support wraps the result in ¬.
2877    ///
2878    /// Coordinated OBJECT LISTS ("Determine each trip's activity, state and year, as
2879    /// well as the friend …") are handled here: the first object's predication is
2880    /// built by [`build_verb_vp_single`], then each comma/and-separated additional
2881    /// object yields its own predication of the SAME verb, all conjoined. A leading
2882    /// determiner/possessor ("each trip's") distributes over the bare coordinate
2883    /// heads (it is replayed before each), while a coordinate carrying its own
2884    /// determiner ("the friend …") is parsed as a fresh NP. No member is dropped.
2885    pub(super) fn build_verb_vp(
2886        &mut self,
2887        subject_symbol: Symbol,
2888        subject_term: Term<'a>,
2889        as_variable: bool,
2890        verb: Symbol,
2891        verb_time: Time,
2892        verb_aspect: Aspect,
2893        verb_class: crate::lexicon::VerbClass,
2894    ) -> ParseResult<&'a LogicExpr<'a>> {
2895        // The leading determiner/possessor that distributes over a coordinate head
2896        // list ("each trip's" in "each trip's activity, state and year"): a
2897        // quantifier optionally followed by a possessive NP, captured as raw tokens
2898        // to replay before each bare coordinate. Empty when the object opens with no
2899        // shared determiner.
2900        let shared_prefix = self.capture_distributive_prefix();
2901        let first = self.build_verb_vp_single(
2902            subject_symbol,
2903            subject_term.clone(),
2904            as_variable,
2905            verb,
2906            verb_time,
2907            verb_aspect,
2908            verb_class,
2909        )?;
2910
2911        let mut combined = first;
2912        loop {
2913            // Consume a coordinator: "," / "and" / ", and" / ", as well as" (the MWE
2914            // collapses "as well as" to And, so ", as well as X" arrives as Comma
2915            // And X). A trailing comma with no following object is not a coordinator.
2916            let mut k = self.current;
2917            let mut saw_coordinator = false;
2918            if matches!(self.tokens.get(k).map(|t| &t.kind), Some(TokenType::Comma)) {
2919                k += 1;
2920                saw_coordinator = true;
2921            }
2922            if matches!(self.tokens.get(k).map(|t| &t.kind), Some(TokenType::And)) {
2923                k += 1;
2924                saw_coordinator = true;
2925            }
2926            if !saw_coordinator {
2927                break;
2928            }
2929            // An object must actually follow the coordinator — a determiner, a
2930            // content word, or a number. Otherwise this is sentential/VP "and" (not
2931            // ours to consume), so leave it for the surrounding parser.
2932            let opens_object = self
2933                .tokens
2934                .get(k)
2935                .map(|t| &t.kind)
2936                .is_some_and(|t| t.is_generalized_quantifier())
2937                || matches!(
2938                    self.tokens.get(k).map(|t| &t.kind),
2939                    Some(TokenType::Article(_))
2940                        | Some(TokenType::All)
2941                        | Some(TokenType::Some)
2942                        | Some(TokenType::No)
2943                        | Some(TokenType::Any)
2944                        | Some(TokenType::Noun(_))
2945                        | Some(TokenType::ProperName(_))
2946                        | Some(TokenType::CalendarUnit(_))
2947                        | Some(TokenType::Ambiguous { .. })
2948                        | Some(TokenType::Number(_))
2949                        | Some(TokenType::Cardinal(_))
2950                );
2951            if !opens_object {
2952                break;
2953            }
2954            // CLAUSE-BOUNDARY GUARD: a determiner/adjective-led NP whose COMMON-NOUN
2955            // head is immediately followed by a finite verb is the SUBJECT of a new
2956            // clause, not a coordinated object — "enters the room, the alarm TRIGGERS"
2957            // must not coordinate "the room, the alarm". So is a bare proper name that
2958            // opens the coordinate: "If a dog barks, JOHN RUNS" is a consequent, not a
2959            // second thing the dog barks. A pure-noun head must be crossed first, so a
2960            // bare ambiguous noun/verb coordinate head ("…, STATE and year") is still
2961            // coordinated and a proper-name reduced relative ("the friend SIMON went
2962            // with") is not mistaken for a clause.
2963            {
2964                let mut p = k;
2965                if self
2966                    .tokens
2967                    .get(p)
2968                    .map(|t| &t.kind)
2969                    .is_some_and(|t| t.is_generalized_quantifier())
2970                    || matches!(
2971                        self.tokens.get(p).map(|t| &t.kind),
2972                        Some(TokenType::Article(_))
2973                            | Some(TokenType::All)
2974                            | Some(TokenType::Some)
2975                            | Some(TokenType::No)
2976                            | Some(TokenType::Any)
2977                    )
2978                {
2979                    p += 1;
2980                }
2981                while matches!(
2982                    self.tokens.get(p).map(|t| &t.kind),
2983                    Some(TokenType::Adjective(_)) | Some(TokenType::NonIntersectiveAdjective(_))
2984                ) {
2985                    p += 1;
2986                }
2987                let head_start = p;
2988                if p == k
2989                    && matches!(
2990                        self.tokens.get(p).map(|t| &t.kind),
2991                        Some(TokenType::ProperName(_))
2992                    )
2993                {
2994                    p += 1;
2995                } else {
2996                    while matches!(
2997                        self.tokens.get(p).map(|t| &t.kind),
2998                        Some(TokenType::Noun(_))
2999                    ) {
3000                        p += 1;
3001                    }
3002                }
3003                let saw_head = p > head_start;
3004                let verb_follows = self.tokens.get(p).map_or(false, |t| {
3005                    self.kind_is_verb(&t.kind)
3006                        || matches!(
3007                            t.kind,
3008                            TokenType::Auxiliary(_)
3009                                | TokenType::Is
3010                                | TokenType::Are
3011                                | TokenType::Was
3012                                | TokenType::Were
3013                                | TokenType::Must
3014                                | TokenType::Can
3015                                | TokenType::Should
3016                                | TokenType::Could
3017                                | TokenType::Would
3018                                | TokenType::May
3019                                | TokenType::Might
3020                                | TokenType::Shall
3021                                | TokenType::Cannot
3022                        )
3023                });
3024                if saw_head && verb_follows {
3025                    break;
3026                }
3027            }
3028            // Commit to consuming the coordinator tokens.
3029            self.current = k;
3030            // A bare coordinate head (no determiner of its own) inherits the shared
3031            // distributive prefix; one with its own determiner is parsed as-is.
3032            let has_own_determiner = self
3033                .tokens
3034                .get(self.current)
3035                .map(|t| &t.kind)
3036                .is_some_and(|t| t.is_generalized_quantifier())
3037                || matches!(
3038                    self.tokens.get(self.current).map(|t| &t.kind),
3039                    Some(TokenType::Article(_))
3040                        | Some(TokenType::All)
3041                        | Some(TokenType::Some)
3042                        | Some(TokenType::No)
3043                        | Some(TokenType::Any)
3044                );
3045            if !has_own_determiner && !shared_prefix.is_empty() {
3046                self.splice_tokens(self.current, &shared_prefix);
3047            }
3048            let next = self.build_verb_vp_single(
3049                subject_symbol,
3050                subject_term.clone(),
3051                as_variable,
3052                verb,
3053                verb_time,
3054                verb_aspect,
3055                verb_class,
3056            )?;
3057            combined = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3058                left: combined,
3059                op: TokenType::And,
3060                right: next,
3061            });
3062        }
3063        Ok(combined)
3064    }
3065
3066    /// Capture the leading distributive determiner/possessor of the object at the
3067    /// cursor as cloned tokens to be replayed before bare coordinate heads — a
3068    /// quantifier (`each`/`every`/…) optionally followed by a possessive NP
3069    /// (`trip 's`). Returns an empty vector and leaves the cursor unchanged when the
3070    /// object opens with no such prefix (a definite article, a bare noun, …).
3071    fn capture_distributive_prefix(&self) -> Vec<Token> {
3072        let mut p = self.current;
3073        let mut prefix: Vec<Token> = Vec::new();
3074        let is_quantifier = self
3075            .tokens
3076            .get(p)
3077            .map(|t| &t.kind)
3078            .is_some_and(|t| t.is_generalized_quantifier())
3079            || matches!(
3080                self.tokens.get(p).map(|t| &t.kind),
3081                Some(TokenType::All)
3082                    | Some(TokenType::Some)
3083                    | Some(TokenType::No)
3084                    | Some(TokenType::Any)
3085            );
3086        if !is_quantifier {
3087            return prefix;
3088        }
3089        prefix.push(self.tokens[p].clone());
3090        p += 1;
3091        // An optional possessive NP head ("trip 's"): one or more nouns then "'s".
3092        let mut q = p;
3093        let mut saw_noun = false;
3094        while matches!(
3095            self.tokens.get(q).map(|t| &t.kind),
3096            Some(TokenType::Noun(_)) | Some(TokenType::Ambiguous { .. })
3097        ) {
3098            saw_noun = true;
3099            q += 1;
3100        }
3101        if saw_noun
3102            && matches!(
3103                self.tokens.get(q).map(|t| &t.kind),
3104                Some(TokenType::Possessive)
3105            )
3106        {
3107            for t in &self.tokens[p..=q] {
3108                prefix.push(t.clone());
3109            }
3110        }
3111        prefix
3112    }
3113
3114    /// Insert `toks` into the token stream at index `at`, shifting the tail right.
3115    fn splice_tokens(&mut self, at: usize, toks: &[Token]) {
3116        for (i, t) in toks.iter().enumerate() {
3117            self.tokens.insert(at + i, t.clone());
3118        }
3119    }
3120
3121    /// Builds the predication for a SINGLE object (see [`build_verb_vp`], which wraps
3122    /// this to coordinate object lists). The caller has consumed the verb.
3123    pub(super) fn build_verb_vp_single(
3124        &mut self,
3125        subject_symbol: Symbol,
3126        subject_term: Term<'a>,
3127        as_variable: bool,
3128        mut verb: Symbol,
3129        verb_time: Time,
3130        verb_aspect: Aspect,
3131        verb_class: crate::lexicon::VerbClass,
3132    ) -> ParseResult<&'a LogicExpr<'a>> {
3133        let mut args = vec![subject_term.clone()];
3134
3135        // Control/raising verb with infinitival complement ("wants to
3136        // play"): route through the canonical control machinery, then
3137        // restore the subject's variable-ness so quantified subjects bind
3138        // into the complement ("Every child wants to play." → W(x, Play(x))).
3139        if self.is_control_verb(verb) && self.check_to() {
3140            let subject_np = NounPhrase {
3141                noun: subject_symbol,
3142                definiteness: None,
3143                adjectives: &[],
3144                possessor: None,
3145                pps: &[],
3146                superlative: None,
3147            };
3148            let control = self.parse_control_structure(&subject_np, verb, verb_time)?;
3149            return if as_variable {
3150                self.substitute_constant_with_var(control, subject_symbol, subject_symbol)
3151            } else {
3152                Ok(control)
3153            };
3154        }
3155
3156        // Arithmetic / vague verbal comparative ("scored 3 points lower
3157        // than Bessie", "scored somewhat higher than Shirley"). Shared
3158        // with parse_atom's inline VP path via try_arithmetic_comparative.
3159        if let Some(cmp) = self.try_arithmetic_comparative(verb, subject_term.clone(), verb_time)? {
3160            return Ok(cmp);
3161        }
3162
3163        // Temporal offset ("performed 2 weeks after Bessie").
3164        if let Some(off) = self.try_temporal_offset(verb, subject_term.clone(), verb_time)? {
3165            return Ok(off);
3166        }
3167
3168        // Ordinal-position offset ("finished 2 places ahead of Bob").
3169        if let Some(off) = self.try_positional_offset(verb, subject_term.clone(), verb_time)? {
3170            return Ok(off);
3171        }
3172
3173        // Verbal comparative ("runs faster than Bob", "run faster than all
3174        // cats"): the comparative grades the event participants — the verb
3175        // event is asserted and the subject compared to the standard.
3176        if let TokenType::Comparative(comp_adj) = self.peek().kind.clone() {
3177            if matches!(
3178                self.tokens.get(self.current + 1).map(|t| t.kind.clone()),
3179                Some(TokenType::Than)
3180            ) {
3181                self.advance(); // comparative
3182                self.advance(); // than
3183
3184                let event_var = self.get_event_var();
3185                let mut modifiers = Vec::new();
3186                let effective_time = self.pending_time.take().unwrap_or(verb_time);
3187                match effective_time {
3188                    Time::Past => modifiers.push(self.interner.intern("Past")),
3189                    Time::Future => modifiers.push(self.interner.intern("Future")),
3190                    _ => {}
3191                }
3192                let suppress_existential = self.drs.in_conditional_antecedent();
3193                let event = self
3194                    .ctx
3195                    .exprs
3196                    .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
3197                        event_var,
3198                        verb,
3199                        roles: self
3200                            .ctx
3201                            .roles
3202                            .alloc_slice(vec![(ThematicRole::Agent, subject_term.clone())]),
3203                        modifiers: self.ctx.syms.alloc_slice(modifiers),
3204                        suppress_existential,
3205                        world: None,
3206                    })));
3207
3208                let result = if self.check_quantifier() {
3209                    let q = self.advance().kind.clone();
3210                    let std_np = self.parse_noun_phrase(false)?;
3211                    let std_var = self.next_var_name();
3212                    let restriction = self.ctx.exprs.alloc(LogicExpr::Predicate {
3213                        name: std_np.noun,
3214                        args: self.ctx.terms.alloc_slice([Term::Variable(std_var)]),
3215                        world: None,
3216                    });
3217                    let comparison = self.ctx.exprs.alloc(LogicExpr::Comparative {
3218                        adjective: comp_adj,
3219                        subject: self.ctx.terms.alloc(subject_term.clone()),
3220                        object: self.ctx.terms.alloc(Term::Variable(std_var)),
3221                        difference: None,
3222                        relation: crate::ast::logic::ComparisonRelation::Greater,
3223                    });
3224                    let quantified = self.quantify_argument(&q, std_var, restriction, comparison);
3225                    self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3226                        left: event,
3227                        op: TokenType::And,
3228                        right: quantified,
3229                    })
3230                } else {
3231                    // A descriptive standard ("faster than Quinn Quade's
3232                    // stamp", "faster than the cat that runs") becomes its own
3233                    // existential entity carrying its possessor/PP/relative
3234                    // clause, so it never collapses onto the subject; a bare
3235                    // name stays a constant.
3236                    let std_np = self.parse_noun_phrase(true)?;
3237                    let has_rel = self.check(&TokenType::Who) || self.check(&TokenType::That);
3238                    let is_desc = has_rel
3239                        || std_np.definiteness.is_some()
3240                        || !std_np.adjectives.is_empty()
3241                        || std_np.possessor.is_some()
3242                        || !std_np.pps.is_empty();
3243                    if is_desc {
3244                        let std_var = self.next_var_name();
3245                        let mut restr = self.nominal_predication(Term::Variable(std_var), &std_np);
3246                        for pp in std_np.pps {
3247                            let pp_sub = self.substitute_pp_placeholder(pp, std_var);
3248                            restr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3249                                left: restr,
3250                                op: TokenType::And,
3251                                right: pp_sub,
3252                            });
3253                        }
3254                        if has_rel {
3255                            self.advance(); // "who" / "that"
3256                            let rel = self.parse_relative_clause(std_var)?;
3257                            restr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3258                                left: restr,
3259                                op: TokenType::And,
3260                                right: rel,
3261                            });
3262                        }
3263                        let comparison = self.ctx.exprs.alloc(LogicExpr::Comparative {
3264                            adjective: comp_adj,
3265                            subject: self.ctx.terms.alloc(subject_term.clone()),
3266                            object: self.ctx.terms.alloc(Term::Variable(std_var)),
3267                            difference: None,
3268                            relation: crate::ast::logic::ComparisonRelation::Greater,
3269                        });
3270                        let body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3271                            left: restr,
3272                            op: TokenType::And,
3273                            right: comparison,
3274                        });
3275                        let quantified = self.ctx.exprs.alloc(LogicExpr::Quantifier {
3276                            kind: QuantifierKind::Existential,
3277                            variable: std_var,
3278                            body,
3279                            island_id: self.current_island,
3280                        });
3281                        self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3282                            left: event,
3283                            op: TokenType::And,
3284                            right: quantified,
3285                        })
3286                    } else {
3287                        let comparison = self.ctx.exprs.alloc(LogicExpr::Comparative {
3288                            adjective: comp_adj,
3289                            subject: self.ctx.terms.alloc(subject_term.clone()),
3290                            object: self.ctx.terms.alloc(Term::Constant(std_np.noun)),
3291                            difference: None,
3292                            relation: crate::ast::logic::ComparisonRelation::Greater,
3293                        });
3294                        self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3295                            left: event,
3296                            op: TokenType::And,
3297                            right: comparison,
3298                        })
3299                    }
3300                };
3301                return Ok(result);
3302            }
3303        }
3304
3305        // Perception small clause ("saw her duck", "watched the bird fly"):
3306        // a perception verb takes "NP bare-VP" naming the PERCEIVED event.
3307        // Gated on an actual Verb token so a Noun-variant parse of the same
3308        // word yields the distinct NP-object reading instead.
3309        if crate::lexicon::is_perception_verb(&self.interner.resolve(verb).to_lowercase()) {
3310            let mut vp_idx = None;
3311            let mut i = self.current;
3312            // A small clause ends where its sentence does, or at a coordinator: in "saw Mary
3313            // and Bill ran" Bill's running is a clause of its own.
3314            while i < self.tokens.len()
3315                && !matches!(
3316                    self.tokens[i].kind,
3317                    TokenType::Period
3318                        | TokenType::EOF
3319                        | TokenType::Comma
3320                        | TokenType::And
3321                        | TokenType::Or
3322                )
3323            {
3324                // Mode-aware verb reading: under noun priority an
3325                // Ambiguous token takes its noun reading, so the small
3326                // clause does not fire and the NP-object parse runs.
3327                let is_verb_reading = match &self.tokens[i].kind {
3328                    TokenType::Verb { .. } => true,
3329                    TokenType::Ambiguous { primary, .. } if !self.noun_priority_mode => {
3330                        matches!(**primary, TokenType::Verb { .. })
3331                    }
3332                    _ => false,
3333                };
3334                if is_verb_reading {
3335                    vp_idx = Some(i);
3336                }
3337                i += 1;
3338            }
3339            if let Some(vp_i) = vp_idx {
3340                if vp_i > self.current {
3341                    let psubj = match self.tokens[vp_i - 1].kind.clone() {
3342                        TokenType::Noun(n) | TokenType::ProperName(n) => Some(n),
3343                        TokenType::Pronoun { .. } | TokenType::Ambiguous { .. } => {
3344                            let lx = self
3345                                .interner
3346                                .resolve(self.tokens[vp_i - 1].lexeme)
3347                                .to_lowercase();
3348                            let cap = lx
3349                                .chars()
3350                                .next()
3351                                .map(|c| c.to_uppercase().collect::<String>() + &lx[1..])
3352                                .unwrap_or(lx);
3353                            Some(self.interner.intern(&cap))
3354                        }
3355                        _ => None,
3356                    };
3357                    if let Some(psubj) = psubj {
3358                        let inner_verb = match &self.tokens[vp_i].kind {
3359                            TokenType::Verb { lemma, .. } => *lemma,
3360                            TokenType::Ambiguous { primary, .. } => {
3361                                if let TokenType::Verb { lemma, .. } = **primary {
3362                                    lemma
3363                                } else {
3364                                    unreachable!("gated on verb reading")
3365                                }
3366                            }
3367                            _ => unreachable!("gated on verb reading"),
3368                        };
3369                        self.current = vp_i + 1; // consume through the VP head
3370                        let perceived = self.ctx.exprs.alloc(LogicExpr::Predicate {
3371                            name: inner_verb,
3372                            args: self.ctx.terms.alloc_slice([Term::Constant(psubj)]),
3373                            world: None,
3374                        });
3375                        let perceived_advs = self.collect_adverbs();
3376                        let perceived = if perceived_advs.is_empty() {
3377                            perceived
3378                        } else {
3379                            self.ctx.exprs.alloc(LogicExpr::Event {
3380                                predicate: perceived,
3381                                adverbs: self.ctx.syms.alloc_slice(perceived_advs),
3382                            })
3383                        };
3384                        let mut modifiers: Vec<Symbol> = Vec::new();
3385                        match verb_time {
3386                            Time::Past => modifiers.push(self.interner.intern("Past")),
3387                            Time::Future => modifiers.push(self.interner.intern("Future")),
3388                            _ => {}
3389                        }
3390                        let event_var = self.get_event_var();
3391                        let suppress_existential = self.drs.in_conditional_antecedent();
3392                        return Ok(self.ctx.exprs.alloc(LogicExpr::NeoEvent(Box::new(
3393                            NeoEventData {
3394                                event_var,
3395                                verb,
3396                                roles: self.ctx.roles.alloc_slice(vec![
3397                                    (ThematicRole::Agent, subject_term.clone()),
3398                                    (ThematicRole::Theme, Term::Proposition(perceived)),
3399                                ]),
3400                                modifiers: self.ctx.syms.alloc_slice(modifiers),
3401                                suppress_existential,
3402                                world: None,
3403                            },
3404                        ))));
3405                    }
3406                }
3407            }
3408        }
3409
3410        // Check for embedded wh-clause: "I know who/what"
3411        if self.check_wh_word() {
3412            let wh_token = self.advance().kind.clone();
3413
3414            let is_who = matches!(wh_token, TokenType::Who);
3415            let is_what = matches!(wh_token, TokenType::What);
3416
3417            // Check for sluicing: wh-word followed by terminator
3418            let is_sluicing =
3419                self.is_at_end() || self.check(&TokenType::Period) || self.check(&TokenType::Comma);
3420
3421            if is_sluicing {
3422                if let Some(template) = self.last_event_template.clone() {
3423                    let wh_var = self.next_var_name();
3424
3425                    let roles: Vec<_> = if is_who {
3426                        std::iter::once((ThematicRole::Agent, Term::Variable(wh_var)))
3427                            .chain(template.non_agent_roles.iter().cloned())
3428                            .collect()
3429                    } else if is_what {
3430                        vec![
3431                            (ThematicRole::Agent, subject_term.clone()),
3432                            (ThematicRole::Theme, Term::Variable(wh_var)),
3433                        ]
3434                    } else {
3435                        std::iter::once((ThematicRole::Agent, Term::Variable(wh_var)))
3436                            .chain(template.non_agent_roles.iter().cloned())
3437                            .collect()
3438                    };
3439
3440                    let event_var = self.get_event_var();
3441                    let suppress_existential = self.drs.in_conditional_antecedent();
3442                    let reconstructed =
3443                        self.ctx
3444                            .exprs
3445                            .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
3446                                event_var,
3447                                verb: template.verb,
3448                                roles: self.ctx.roles.alloc_slice(roles),
3449                                modifiers: self.ctx.syms.alloc_slice(template.modifiers.clone()),
3450                                suppress_existential,
3451                                world: None,
3452                            })));
3453
3454                    let question = self.ctx.exprs.alloc(LogicExpr::Question {
3455                        wh_variable: wh_var,
3456                        body: reconstructed,
3457                    });
3458
3459                    let know_event =
3460                        self.ctx
3461                            .exprs
3462                            .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
3463                                event_var: self.get_event_var(),
3464                                verb,
3465                                roles: self.ctx.roles.alloc_slice(vec![
3466                                    (ThematicRole::Agent, subject_term),
3467                                    (ThematicRole::Theme, Term::Proposition(question)),
3468                                ]),
3469                                modifiers: self.ctx.syms.alloc_slice(vec![]),
3470                                suppress_existential,
3471                                world: None,
3472                            })));
3473
3474                    return Ok(know_event);
3475                }
3476            }
3477
3478            // Non-sluicing: "I know who runs"
3479            let embedded = self.parse_embedded_wh_clause()?;
3480            let question = self.ctx.exprs.alloc(LogicExpr::Question {
3481                wh_variable: self.interner.intern("x"),
3482                body: embedded,
3483            });
3484
3485            let suppress_existential = self.drs.in_conditional_antecedent();
3486            let know_event = self
3487                .ctx
3488                .exprs
3489                .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
3490                    event_var: self.get_event_var(),
3491                    verb,
3492                    roles: self.ctx.roles.alloc_slice(vec![
3493                        (ThematicRole::Agent, subject_term),
3494                        (ThematicRole::Theme, Term::Proposition(question)),
3495                    ]),
3496                    modifiers: self.ctx.syms.alloc_slice(vec![]),
3497                    suppress_existential,
3498                    world: None,
3499                })));
3500
3501            return Ok(know_event);
3502        }
3503
3504        // Opaque attitude verbs take a finite clausal complement as a STRUCTURED
3505        // PROPOSITION (P3), not an extensional object: "John believes Mary left."
3506        // → Believe(John, ⟨Left(Mary)⟩). A pure-token lookahead detects an
3507        // embedded proper-name/pronoun subject directly followed by a verb
3508        // (optionally after the complementizer "that"); article-headed embedded
3509        // clauses ("a spy exists") are already handled downstream and untouched.
3510        if crate::lexicon::is_opaque_verb(&self.interner.resolve(verb).to_lowercase()) {
3511            let mut i = self.current;
3512            if i < self.tokens.len() && matches!(self.tokens[i].kind, TokenType::That) {
3513                i += 1;
3514            }
3515            let subj_is_name_or_pronoun = i < self.tokens.len()
3516                && matches!(
3517                    self.tokens[i].kind,
3518                    TokenType::ProperName(_) | TokenType::Pronoun { .. }
3519                );
3520            let verb_follows = subj_is_name_or_pronoun
3521                && i + 1 < self.tokens.len()
3522                && matches!(
3523                    self.tokens[i + 1].kind,
3524                    TokenType::Verb { .. } | TokenType::Auxiliary(_)
3525                );
3526            // Article-headed embedded subject with a finite clause:
3527            // "believes that THE TEACHER wants …". (Indefinite objects
3528            // without a following verb keep the de re/de dicto path.)
3529            let definite_np_clause = i + 2 < self.tokens.len()
3530                && matches!(self.tokens[i].kind, TokenType::Article(_))
3531                && matches!(self.tokens[i + 1].kind, TokenType::Noun(_))
3532                && matches!(
3533                    self.tokens[i + 2].kind,
3534                    TokenType::Verb { .. } | TokenType::Auxiliary(_)
3535                );
3536            if verb_follows || definite_np_clause {
3537                if self.check(&TokenType::That) {
3538                    self.advance();
3539                }
3540                let embedded_subject = match self.peek().kind {
3541                    TokenType::ProperName(s) => {
3542                        self.advance();
3543                        s
3544                    }
3545                    TokenType::Pronoun { gender, number, .. } => {
3546                        self.advance();
3547                        match self.resolve_pronoun(gender, number)? {
3548                            super::ResolvedPronoun::Variable(s)
3549                            | super::ResolvedPronoun::Constant(s) => s,
3550                        }
3551                    }
3552                    TokenType::Article(_) => {
3553                        let np = self.parse_noun_phrase(false)?;
3554                        np.noun
3555                    }
3556                    _ => unreachable!("guarded by subj_is_name_or_pronoun"),
3557                };
3558                let embedded_pred = self.parse_predicate_with_subject(embedded_subject)?;
3559                let embedded_term = Term::Proposition(embedded_pred);
3560                let main_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
3561                    name: verb,
3562                    args: self
3563                        .ctx
3564                        .terms
3565                        .alloc_slice([subject_term.clone(), embedded_term]),
3566                    world: None,
3567                });
3568                let effective_time = self.pending_time.take().unwrap_or(verb_time);
3569                return Ok(if effective_time == Time::Past {
3570                    self.ctx.exprs.alloc(LogicExpr::Temporal {
3571                        operator: TemporalOperator::Past,
3572                        body: main_pred,
3573                    })
3574                } else {
3575                    main_pred
3576                });
3577            }
3578        }
3579
3580        let mut object_term: Option<Term<'a>> = None;
3581        let mut second_object_term: Option<Term<'a>> = None;
3582        // "X has Y as [its] ROLE" — a predicative secondary naming the role Y
3583        // fills (set after the object is parsed; conjoined as Role(Y) below).
3584        let mut as_role: Option<Symbol> = None;
3585        // A filler-gap object licenses a stranded preposition ("Who did John talk to?").
3586        let mut gap_object = false;
3587        let mut object_pps: &[&LogicExpr<'a>] = &[]; // PPs attached to object NP (for NP-attachment mode)
3588        let mut object_adjectives: &[Symbol] = &[]; // adjectives on a definite/constant object ("the GREEN shirt")
3589        if self.check(&TokenType::Reflexive) {
3590            self.advance();
3591            // The reflexive binds the subject TERM, preserving its
3592            // variable-ness under a quantified subject ("Every man loves
3593            // himself." → Theme(e, x), not a constant).
3594            let term = subject_term.clone();
3595            object_term = Some(term.clone());
3596            args.push(term);
3597        } else if self.check_pronoun()
3598            && !(self.check_possessive_pronoun()
3599                && match self.tokens.get(self.current + 1).map(|t| t.kind.clone()) {
3600                    Some(TokenType::Noun(_)) => true,
3601                    // Under noun priority an Ambiguous next token reads as
3602                    // a noun, so "her duck" is a possessive NP object.
3603                    Some(TokenType::Ambiguous { .. }) => self.noun_priority_mode,
3604                    _ => false,
3605                })
3606        {
3607            let token = self.advance().clone();
3608            let (gender, number) = match &token.kind {
3609                TokenType::Pronoun { gender, number, .. } => (*gender, *number),
3610                TokenType::Ambiguous {
3611                    primary,
3612                    alternatives,
3613                } => {
3614                    if let TokenType::Pronoun { gender, number, .. } = **primary {
3615                        (gender, number)
3616                    } else {
3617                        alternatives
3618                            .iter()
3619                            .find_map(|t| {
3620                                if let TokenType::Pronoun { gender, number, .. } = t {
3621                                    Some((*gender, *number))
3622                                } else {
3623                                    None
3624                                }
3625                            })
3626                            .unwrap_or((Gender::Unknown, Number::Singular))
3627                    }
3628                }
3629                _ => (Gender::Unknown, Number::Singular),
3630            };
3631
3632            // Person deictics (§8.4) resolve to the discourse roles in any
3633            // position: object "you" → Addressee, "me" → Speaker.
3634            let plex = self.interner.resolve(token.lexeme).to_lowercase();
3635            let term = match plex.as_str() {
3636                "you" | "yourself" => Term::Constant(self.interner.intern("Addressee")),
3637                "me" | "myself" | "i" => Term::Constant(self.interner.intern("Speaker")),
3638                // A donkey antecedent (indefinite from a quantifier's
3639                // restriction) outranks discourse resolution: "Every man
3640                // who owns a book reads it." → Theme(e, y).
3641                _ => match self.resolve_donkey_pronoun(gender) {
3642                    Some(donkey_var) => Term::Variable(donkey_var),
3643                    None => match self.resolve_pronoun(gender, number)? {
3644                        super::ResolvedPronoun::Variable(s) => Term::Variable(s),
3645                        super::ResolvedPronoun::Constant(s) => Term::Constant(s),
3646                    },
3647                },
3648            };
3649            object_term = Some(term);
3650            args.push(term);
3651
3652            let verb_str = self.interner.resolve(verb);
3653            if Lexer::is_ditransitive_verb(verb_str)
3654                && (self.check_content_word() || self.check_article())
3655            {
3656                let second_np = self.parse_noun_phrase(false)?;
3657                let second_term = Term::Constant(second_np.noun);
3658                second_object_term = Some(second_term);
3659                args.push(second_term);
3660            }
3661        } else if self.peek_definite_reduced_relative_object() {
3662            // A definite object whose head carries a REDUCED OBJECT RELATIVE
3663            // ("Determine the friend Simon went with"). Parse the WHOLE NP —
3664            // article included — so `parse_noun_phrase` runs its reduced-relative
3665            // machinery and returns the relative as a `_PP_SELF_` PP over the
3666            // head. Pre-consuming the article (the generic definite path) would
3667            // hide the determiner and strand the relative's verb. The head noun
3668            // and the relative both survive: the PP is rebound to the object
3669            // constant by the shared object-PP application below. Parsed GREEDILY
3670            // so the reduced relative — a genuine head restrictor, gated above the
3671            // non-greedy PP cutoff — attaches; the precise dispatch guard keeps
3672            // this from over-consuming any other construction.
3673            self.nominal_np_context = true;
3674            let object_np_result = self.parse_noun_phrase(true);
3675            self.nominal_np_context = false;
3676            let object_np = object_np_result?;
3677
3678            let obj_gender = Self::infer_noun_gender(self.interner.resolve(object_np.noun));
3679            let obj_number = if Self::is_plural_noun(self.interner.resolve(object_np.noun)) {
3680                Number::Plural
3681            } else {
3682                Number::Singular
3683            };
3684            self.drs.introduce_referent_with_source(
3685                object_np.noun,
3686                object_np.noun,
3687                obj_gender,
3688                obj_number,
3689                ReferentSource::MainClause,
3690            );
3691
3692            let term = Term::Constant(object_np.noun);
3693            object_term = Some(term);
3694            object_pps = object_np.pps;
3695            object_adjectives = object_np.adjectives;
3696            args.push(term);
3697        } else if self.counting_np_lookahead().is_some()
3698            || self.check_quantifier()
3699            || self.check_article()
3700            || self.check_possessive_pronoun()
3701        {
3702            let obj_quantifier = if let Some(n) = self.counting_np_lookahead() {
3703                // A digit-led counting NP object ("saw 6 brown manatees"):
3704                // consume the integer and quantify the remaining
3705                // "(adjective)+ noun" as ∃=n, reusing the canonical
3706                // quantified-object construction below. Without this the
3707                // adjective is mis-read as a measure unit (→ a bogus
3708                // Recipient role and a dropped count).
3709                self.advance();
3710                Some(TokenType::Cardinal(n))
3711            } else if self.check_possessive_pronoun() {
3712                // Possessive NP object ("his dog"): parse_noun_phrase
3713                // consumes the possessor; no quantifier wrapper.
3714                None
3715            } else if self.check_quantifier() {
3716                Some(self.advance().kind.clone())
3717            } else {
3718                let art = self.advance().kind.clone();
3719                if let TokenType::Article(def) = art {
3720                    if def == Definiteness::Indefinite {
3721                        Some(TokenType::Some)
3722                    } else {
3723                        None
3724                    }
3725                } else {
3726                    None
3727                }
3728            };
3729
3730            // The quantifier/article/cardinal just established this as an NP,
3731            // so a verb-word head after an adjective is a deverbal noun.
3732            self.nominal_np_context = true;
3733            let object_np_result = self.parse_noun_phrase(false);
3734            self.nominal_np_context = false;
3735            let object_np = object_np_result?;
3736
3737            if let Some(obj_q) = obj_quantifier {
3738                let obj_var = self.next_var_name();
3739
3740                // Introduce object referent in DRS for cross-sentence anaphora
3741                let obj_gender = Self::infer_noun_gender(self.interner.resolve(object_np.noun));
3742                let obj_number = if Self::is_plural_noun(self.interner.resolve(object_np.noun)) {
3743                    Number::Plural
3744                } else {
3745                    Number::Singular
3746                };
3747                // Definite descriptions presuppose existence, so they should be globally
3748                // accessible; an indefinite lives where its scope puts it.
3749                let scope = if object_np.definiteness == Some(Definiteness::Definite) {
3750                    self.drs.introduce_referent_with_source(
3751                        obj_var,
3752                        object_np.noun,
3753                        obj_gender,
3754                        obj_number,
3755                        ReferentSource::MainClause,
3756                    );
3757                    IndefiniteScope::Local
3758                } else {
3759                    self.introduce_indefinite(obj_var, object_np.noun, obj_gender, obj_number)
3760                };
3761
3762                let mut obj_restriction: &'a LogicExpr<'a> =
3763                    self.ctx.exprs.alloc(LogicExpr::Predicate {
3764                        name: object_np.noun,
3765                        args: self.ctx.terms.alloc_slice([Term::Variable(obj_var)]),
3766                        world: None,
3767                    });
3768                // A quantified object's own restrictors — adjectives ("a RED
3769                // book") and PPs ("a maximum range OF 475 ft" → Range(o) ∧
3770                // Of(o, 475 ft)) — must survive; dropping them is meaning loss.
3771                for &adj in object_np.adjectives {
3772                    let adj_pred = self.adjective_restriction(adj, obj_var, object_np.noun);
3773                    obj_restriction = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3774                        left: obj_restriction,
3775                        op: TokenType::And,
3776                        right: adj_pred,
3777                    });
3778                }
3779                for pp in object_np.pps {
3780                    let pp_sub = self.substitute_pp_placeholder(pp, obj_var);
3781                    obj_restriction = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3782                        left: obj_restriction,
3783                        op: TokenType::And,
3784                        right: pp_sub,
3785                    });
3786                }
3787
3788                // Continuations inside the object quantifier's scope: a
3789                // second object ("gave some student a book"), a recipient
3790                // ("gave a book to Mary", "… to some teacher"), or an
3791                // object-control infinitive ("caused all flowers to bloom").
3792                let verb_str = self.interner.resolve(verb).to_string();
3793                let mut second_object: Option<Term<'a>> = None;
3794                let mut recipient: Option<Term<'a>> = None;
3795                let mut recipient_quant: Option<(TokenType, Symbol, Symbol)> = None;
3796                let mut control_infinitive: Option<Symbol> = None;
3797
3798                if Lexer::is_ditransitive_verb(&verb_str)
3799                    && (self.check_content_word() || self.check_article())
3800                {
3801                    let second_np = self.parse_noun_phrase(false)?;
3802                    second_object = Some(Term::Constant(second_np.noun));
3803                } else if self.check_to_marker() {
3804                    let after_to = self.tokens.get(self.current + 1).map(|t| t.kind.clone());
3805                    match after_to {
3806                        Some(TokenType::Verb { lemma, .. }) => {
3807                            self.advance(); // to
3808                            self.advance(); // infinitive verb
3809                            control_infinitive = Some(lemma);
3810                        }
3811                        // After a preposition the lexer may classify the
3812                        // infinitive as a noun ("to bloom"); the lexicon
3813                        // recovers the verb reading.
3814                        Some(TokenType::Noun(word))
3815                            if crate::lexicon::lookup_verb_db(
3816                                &self.interner.resolve(word).to_lowercase(),
3817                            )
3818                            .is_some() =>
3819                        {
3820                            let lemma_str = crate::lexicon::lookup_verb_db(
3821                                &self.interner.resolve(word).to_lowercase(),
3822                            )
3823                            .map(|m| m.lemma)
3824                            .unwrap();
3825                            self.advance(); // to
3826                            self.advance(); // infinitive verb (noun-classified)
3827                            control_infinitive = Some(self.interner.intern(lemma_str));
3828                        }
3829                        Some(kind)
3830                            if Lexer::is_ditransitive_verb(&verb_str)
3831                                && QuantifierKind::of_determiner(&kind).is_some() =>
3832                        {
3833                            self.advance(); // to
3834                            let r_quant = self.advance().kind.clone();
3835                            let r_np = self.parse_noun_phrase(false)?;
3836                            let r_var = self.next_var_name();
3837                            recipient_quant = Some((r_quant, r_var, r_np.noun));
3838                        }
3839                        Some(kind)
3840                            if Lexer::is_ditransitive_verb(&verb_str)
3841                                && matches!(
3842                                    kind,
3843                                    TokenType::ProperName(_)
3844                                        | TokenType::Noun(_)
3845                                        | TokenType::Article(_)
3846                                ) =>
3847                        {
3848                            self.advance(); // to
3849                            let r_np = self.parse_noun_phrase(false)?;
3850                            recipient = Some(Term::Constant(r_np.noun));
3851                        }
3852                        _ => {}
3853                    }
3854                }
3855
3856                let event_var = self.get_event_var();
3857                let mut modifiers = self.collect_adverbs();
3858                let effective_time = self.pending_time.take().unwrap_or(verb_time);
3859                match effective_time {
3860                    Time::Past => modifiers.push(self.interner.intern("Past")),
3861                    Time::Future => modifiers.push(self.interner.intern("Future")),
3862                    _ => {}
3863                }
3864
3865                let mut roles = vec![(ThematicRole::Agent, subject_term.clone())];
3866                if let Some(second) = second_object {
3867                    roles.push((ThematicRole::Recipient, Term::Variable(obj_var)));
3868                    roles.push((ThematicRole::Theme, second));
3869                } else {
3870                    roles.push((ThematicRole::Theme, Term::Variable(obj_var)));
3871                    if let Some(r) = recipient {
3872                        roles.push((ThematicRole::Recipient, r));
3873                    } else if let Some((_, r_var, _)) = recipient_quant {
3874                        roles.push((ThematicRole::Recipient, Term::Variable(r_var)));
3875                    }
3876                }
3877
3878                let suppress_existential = self.drs.in_conditional_antecedent();
3879                let neo_event = if let Some(inf) = control_infinitive {
3880                    let inf_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
3881                        name: inf,
3882                        args: self.ctx.terms.alloc_slice([Term::Variable(obj_var)]),
3883                        world: None,
3884                    });
3885                    let control = self.ctx.exprs.alloc(LogicExpr::Control {
3886                        verb,
3887                        subject: self.ctx.terms.alloc(subject_term.clone()),
3888                        object: Some(&*self.ctx.terms.alloc(Term::Variable(obj_var))),
3889                        infinitive: inf_pred,
3890                    });
3891                    match effective_time {
3892                        Time::Past => &*self.ctx.exprs.alloc(LogicExpr::Temporal {
3893                            operator: TemporalOperator::Past,
3894                            body: control,
3895                        }),
3896                        Time::Future => &*self.ctx.exprs.alloc(LogicExpr::Temporal {
3897                            operator: TemporalOperator::Future,
3898                            body: control,
3899                        }),
3900                        _ => control,
3901                    }
3902                } else {
3903                    let plain = self
3904                        .ctx
3905                        .exprs
3906                        .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
3907                            event_var,
3908                            verb,
3909                            roles: self.ctx.roles.alloc_slice(roles),
3910                            modifiers: self.ctx.syms.alloc_slice(modifiers),
3911                            suppress_existential,
3912                            world: None,
3913                        })));
3914                    if let Some((r_quant, r_var, r_noun)) = recipient_quant {
3915                        let r_restriction = self.ctx.exprs.alloc(LogicExpr::Predicate {
3916                            name: r_noun,
3917                            args: self.ctx.terms.alloc_slice([Term::Variable(r_var)]),
3918                            world: None,
3919                        });
3920                        self.quantify_argument(&r_quant, r_var, r_restriction, plain)
3921                    } else {
3922                        plain
3923                    }
3924                };
3925
3926                // Trailing event-PP adjuncts ("takes a holiday WITH a friend TO
3927                // some location") attach to the event INSIDE the object's
3928                // existential scope — the non-quantified path does this inline.
3929                let neo_event = self.attach_trailing_event_pps(neo_event, event_var)?;
3930
3931                // An indefinite object of an if-clause takes the DRS's universal over the
3932                // whole conditional, not an existential of its own.
3933                if obj_q == TokenType::Some && scope == IndefiniteScope::Antecedent {
3934                    return Ok(self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3935                        left: obj_restriction,
3936                        op: TokenType::And,
3937                        right: neo_event,
3938                    }));
3939                }
3940
3941                return Ok(self.quantify_argument(&obj_q, obj_var, obj_restriction, neo_event));
3942            } else {
3943                // Definite object NP (e.g., "the house")
3944                // Introduce to DRS for cross-sentence bridging anaphora
3945                // E.g., "John entered the house. The door was open." - door bridges to house
3946                if object_np.definiteness == Some(Definiteness::Definite) {
3947                    let obj_gender = Self::infer_noun_gender(self.interner.resolve(object_np.noun));
3948                    let obj_number = if Self::is_plural_noun(self.interner.resolve(object_np.noun))
3949                    {
3950                        Number::Plural
3951                    } else {
3952                        Number::Singular
3953                    };
3954                    // Definite descriptions presuppose existence, so they should be globally accessible
3955                    self.drs.introduce_referent_with_source(
3956                        object_np.noun,
3957                        object_np.noun,
3958                        obj_gender,
3959                        obj_number,
3960                        ReferentSource::MainClause,
3961                    );
3962                }
3963
3964                let term = Term::Constant(object_np.noun);
3965                object_term = Some(term);
3966                // Store the definite object's adjectives + PPs so they are
3967                // predicated of the object ("ate the RED apple" → Red(Apple));
3968                // dropping them is a meaning-loss parse.
3969                object_pps = object_np.pps;
3970                object_adjectives = object_np.adjectives;
3971                args.push(term);
3972
3973                // Ditransitive with a DEFINITE indirect object: "gave the
3974                // winner the prize" — the definite IO took this non-quantified
3975                // branch (a definite article carries no obj_quantifier), so the
3976                // direct object must still be picked up here, mirroring the
3977                // proper-name/quantified IO paths. The double-object builder
3978                // then assigns Recipient(IO) ∧ Theme(DO); without this the DO
3979                // strands as a trailing token.
3980                let verb_str = self.interner.resolve(verb);
3981                if Lexer::is_ditransitive_verb(verb_str)
3982                    && (self.check_content_word() || self.check_article())
3983                {
3984                    let second_np = self.parse_noun_phrase(false)?;
3985                    let second_term = Term::Constant(second_np.noun);
3986                    second_object_term = Some(second_term);
3987                    args.push(second_term);
3988                }
3989            }
3990        } else if self.check_focus() {
3991            let focus_kind = if let TokenType::Focus(k) = self.advance().kind {
3992                k
3993            } else {
3994                FocusKind::Only
3995            };
3996
3997            let event_var = self.get_event_var();
3998            let mut modifiers = self.collect_adverbs();
3999            let effective_time = self.pending_time.take().unwrap_or(verb_time);
4000            match effective_time {
4001                Time::Past => modifiers.push(self.interner.intern("Past")),
4002                Time::Future => modifiers.push(self.interner.intern("Future")),
4003                _ => {}
4004            }
4005
4006            if self.check_preposition() {
4007                let prep_token = self.advance().clone();
4008                let prep_name = if let TokenType::Preposition(sym) = prep_token.kind {
4009                    sym
4010                } else {
4011                    self.interner.intern("to")
4012                };
4013                let pp_obj = self.parse_noun_phrase(false)?;
4014                let pp_obj_term = Term::Constant(pp_obj.noun);
4015
4016                let roles = vec![(ThematicRole::Agent, subject_term)];
4017                let suppress_existential = self.drs.in_conditional_antecedent();
4018                let neo_event = self
4019                    .ctx
4020                    .exprs
4021                    .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
4022                        event_var,
4023                        verb,
4024                        roles: self.ctx.roles.alloc_slice(roles),
4025                        modifiers: self.ctx.syms.alloc_slice(modifiers),
4026                        suppress_existential,
4027                        world: None,
4028                    })));
4029
4030                let pp_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
4031                    name: prep_name,
4032                    args: self
4033                        .ctx
4034                        .terms
4035                        .alloc_slice([Term::Variable(event_var), pp_obj_term]),
4036                    world: None,
4037                });
4038
4039                let with_pp = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
4040                    left: neo_event,
4041                    op: TokenType::And,
4042                    right: pp_pred,
4043                });
4044
4045                let focused_ref = self.ctx.terms.alloc(pp_obj_term);
4046                return Ok(self.ctx.exprs.alloc(LogicExpr::Focus {
4047                    kind: focus_kind,
4048                    focused: focused_ref,
4049                    scope: with_pp,
4050                }));
4051            }
4052
4053            let focused_np = self.parse_noun_phrase(false)?;
4054            let focused_term = Term::Constant(focused_np.noun);
4055            args.push(focused_term);
4056
4057            let roles = vec![
4058                (ThematicRole::Agent, subject_term),
4059                (ThematicRole::Theme, focused_term),
4060            ];
4061
4062            let suppress_existential = self.drs.in_conditional_antecedent();
4063            let neo_event = self
4064                .ctx
4065                .exprs
4066                .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
4067                    event_var,
4068                    verb,
4069                    roles: self.ctx.roles.alloc_slice(roles),
4070                    modifiers: self.ctx.syms.alloc_slice(modifiers),
4071                    suppress_existential,
4072                    world: None,
4073                })));
4074
4075            let focused_ref = self.ctx.terms.alloc(focused_term);
4076            return Ok(self.ctx.exprs.alloc(LogicExpr::Focus {
4077                kind: focus_kind,
4078                focused: focused_ref,
4079                scope: neo_event,
4080            }));
4081        } else if self.check(&TokenType::Either) {
4082            // "danced either the hustle or the lindy" → Dance(S,Hustle) ∨ Dance(S,Lindy)
4083            self.advance(); // consume "either"
4084            let np1 = self.parse_noun_phrase(true)?;
4085            if self.check(&TokenType::Or) {
4086                self.advance(); // consume "or"
4087                let np2 = self.parse_noun_phrase(true)?;
4088                let effective_time = self.pending_time.take().unwrap_or(verb_time);
4089                let placeholder = self.interner.intern("_PP_SELF_");
4090                let possesses = self.interner.intern("Possesses");
4091                // Build a disjunct's predication, KEEPING the object NP's
4092                // possessor and PPs ("either the hustle from Spain or …"
4093                // must not drop "from Spain"; "either Tara's routine or …"
4094                // must not drop the possessor).
4095                let build = |p: &mut Self, np: &NounPhrase<'a>| -> &'a LogicExpr<'a> {
4096                    let obj = Term::Constant(np.noun);
4097                    let mut pred: &'a LogicExpr<'a> = p.ctx.exprs.alloc(LogicExpr::Predicate {
4098                        name: verb,
4099                        args: p.ctx.terms.alloc_slice([subject_term, obj]),
4100                        world: None,
4101                    });
4102                    if let Some(possessor) = np.possessor {
4103                        let poss = p.ctx.exprs.alloc(LogicExpr::Predicate {
4104                            name: possesses,
4105                            args: p
4106                                .ctx
4107                                .terms
4108                                .alloc_slice([Term::Constant(possessor.noun), obj]),
4109                            world: None,
4110                        });
4111                        pred = p.ctx.exprs.alloc(LogicExpr::BinaryOp {
4112                            left: pred,
4113                            op: TokenType::And,
4114                            right: poss,
4115                        });
4116                    }
4117                    for pp in np.pps {
4118                        let pp_sub = match pp {
4119                            LogicExpr::Predicate { name, args, world } => {
4120                                let new_args: Vec<Term<'a>> = args
4121                                    .iter()
4122                                    .map(|a| match a {
4123                                        Term::Variable(v) if *v == placeholder => obj,
4124                                        other => *other,
4125                                    })
4126                                    .collect();
4127                                p.ctx.exprs.alloc(LogicExpr::Predicate {
4128                                    name: *name,
4129                                    args: p.ctx.terms.alloc_slice(new_args),
4130                                    world: *world,
4131                                })
4132                            }
4133                            other => *other,
4134                        };
4135                        pred = p.ctx.exprs.alloc(LogicExpr::BinaryOp {
4136                            left: pred,
4137                            op: TokenType::And,
4138                            right: pp_sub,
4139                        });
4140                    }
4141                    pred
4142                };
4143                let pred1 = build(self, &np1);
4144                let pred2 = build(self, &np2);
4145                let wrap_time = |p: &mut Self, e: &'a LogicExpr<'a>| -> &'a LogicExpr<'a> {
4146                    if effective_time == Time::Past {
4147                        p.ctx.exprs.alloc(LogicExpr::Temporal {
4148                            operator: TemporalOperator::Past,
4149                            body: e,
4150                        })
4151                    } else {
4152                        e
4153                    }
4154                };
4155                let pred1 = wrap_time(self, pred1);
4156                let pred2 = wrap_time(self, pred2);
4157                return Ok(self.ctx.exprs.alloc(LogicExpr::BinaryOp {
4158                    left: pred1,
4159                    op: TokenType::Or,
4160                    right: pred2,
4161                }));
4162            }
4163            // No "or" — fall through with np1 as plain object
4164            let term = Term::Constant(np1.noun);
4165            object_term = Some(term);
4166            args.push(term);
4167        } else if self.check_number() {
4168            let measure = self.parse_measure_phrase()?;
4169            // The measured quantity is the verb's Theme ("scored 190 points"
4170            // → Theme(e, 190 points)); without this the count is parsed but
4171            // never reaches a thematic role and the number is lost.
4172            object_term = Some(*measure);
4173            if self.check_content_word() {
4174                let noun_sym = self.consume_content_word()?;
4175                args.push(*measure);
4176                args.push(Term::Constant(noun_sym));
4177            } else {
4178                args.push(*measure);
4179            }
4180        } else if self.check_content_word() {
4181            let potential_object = self.parse_noun_phrase(false)?;
4182            // Store the object's adjectives + PPs for NP-attachment mode
4183            object_pps = potential_object.pps;
4184            object_adjectives = potential_object.adjectives;
4185
4186            // A finite clausal complement (the NP is followed by a verb) is taken
4187            // as a structured proposition (P3) when the matrix verb is an opaque
4188            // attitude verb ("John believes Mary left." → Believe(John, ⟨Left(Mary)⟩))
4189            // or in a filler-gap context. The complement keeps its own structure
4190            // so co-intensional complements stay distinct and substitution into it
4191            // is blocked.
4192            let verb_is_opaque =
4193                crate::lexicon::is_opaque_verb(&self.interner.resolve(verb).to_lowercase());
4194            if self.check_verb() && (self.filler_gap.is_some() || verb_is_opaque) {
4195                let embedded_subject = potential_object.noun;
4196                let embedded_pred = self.parse_predicate_with_subject(embedded_subject)?;
4197
4198                let embedded_term = Term::Proposition(embedded_pred);
4199                let main_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
4200                    name: verb,
4201                    args: self.ctx.terms.alloc_slice([subject_term, embedded_term]),
4202                    world: None,
4203                });
4204
4205                let effective_time = self.pending_time.take().unwrap_or(verb_time);
4206                return Ok(if effective_time == Time::Past {
4207                    self.ctx.exprs.alloc(LogicExpr::Temporal {
4208                        operator: TemporalOperator::Past,
4209                        body: main_pred,
4210                    })
4211                } else {
4212                    main_pred
4213                });
4214            }
4215
4216            // A single subject and a single object pair trivially ("… respectively"). A
4217            // list of objects is coordinated by `build_verb_vp`, one event per object.
4218            if self.check(&TokenType::Respectively) {
4219                self.advance(); // consume "respectively"
4220            }
4221
4222            let term = Term::Constant(potential_object.noun);
4223            object_term = Some(term);
4224            args.push(term);
4225
4226            let verb_str = self.interner.resolve(verb);
4227            if Lexer::is_ditransitive_verb(verb_str)
4228                && (self.check_content_word() || self.check_article())
4229            {
4230                let second_np = self.parse_noun_phrase(false)?;
4231                let second_term = Term::Constant(second_np.noun);
4232                second_object_term = Some(second_term);
4233                args.push(second_term);
4234            }
4235        } else if self.filler_gap.is_some() && !self.check_content_word() && !self.check_pronoun() {
4236            let gap_var = self.filler_gap.take().unwrap();
4237            let term = Term::Variable(gap_var);
4238            object_term = Some(term);
4239            args.push(term);
4240            gap_object = true;
4241        }
4242
4243        let unknown = self.interner.intern("?");
4244        let mut pp_predicates: Vec<&'a LogicExpr<'a>> = Vec::new();
4245
4246        // Check for distanced phrasal verb particle: "gave the book up"
4247        if let TokenType::Particle(particle_sym) = self.peek().kind {
4248            let verb_str = self.interner.resolve(verb).to_lowercase();
4249            let particle_str = self.interner.resolve(particle_sym).to_lowercase();
4250            if let Some((phrasal_lemma, _class)) =
4251                crate::lexicon::lookup_phrasal_verb(&verb_str, &particle_str)
4252            {
4253                self.advance(); // consume the particle
4254                verb = self.interner.intern(phrasal_lemma);
4255            } else {
4256                // A particle with no phrasal-verb table entry ("came OUT",
4257                // "went UP") — keep it as a particle predicate over the event so
4258                // a trailing PP still attaches ("came out IN 1995"). The
4259                // clause-final case is handled in the PP loop; this covers the
4260                // particle-then-PP case it misses.
4261                self.advance(); // consume the particle
4262                let event_sym = self.get_event_var();
4263                let cap = {
4264                    let p = self.interner.resolve(particle_sym);
4265                    let mut chs = p.chars();
4266                    match chs.next() {
4267                        Some(f) => f.to_uppercase().collect::<String>() + chs.as_str(),
4268                        None => String::new(),
4269                    }
4270                };
4271                pp_predicates.push(self.ctx.exprs.alloc(LogicExpr::Predicate {
4272                    name: self.interner.intern(&cap),
4273                    args: self.ctx.terms.alloc_slice([Term::Variable(event_sym)]),
4274                    world: None,
4275                }));
4276            }
4277        }
4278        while self.check_preposition() || self.check_to() {
4279            // "within N cycles" is a temporal bound, not a PP — leave for try_wrap_bounded_delay
4280            if self.check_preposition_is("within")
4281                && self.current + 1 < self.tokens.len()
4282                && matches!(
4283                    self.tokens[self.current + 1].kind,
4284                    TokenType::Cardinal(_) | TokenType::Number(_)
4285                )
4286            {
4287                break;
4288            }
4289            let prep_token = self.advance().clone();
4290            let prep_name = if let TokenType::Preposition(sym) = prep_token.kind {
4291                sym
4292            } else if matches!(prep_token.kind, TokenType::To) {
4293                self.interner.intern("To")
4294            } else {
4295                continue;
4296            };
4297
4298            let pp_obj_term = if self.check(&TokenType::Reflexive) {
4299                self.advance();
4300                Term::Constant(subject_symbol)
4301            } else if self.check_pronoun() {
4302                let token = self.advance().clone();
4303                let (gender, number) = match &token.kind {
4304                    TokenType::Pronoun { gender, number, .. } => (*gender, *number),
4305                    TokenType::Ambiguous {
4306                        primary,
4307                        alternatives,
4308                    } => {
4309                        if let TokenType::Pronoun { gender, number, .. } = **primary {
4310                            (gender, number)
4311                        } else {
4312                            alternatives
4313                                .iter()
4314                                .find_map(|t| {
4315                                    if let TokenType::Pronoun { gender, number, .. } = t {
4316                                        Some((*gender, *number))
4317                                    } else {
4318                                        None
4319                                    }
4320                                })
4321                                .unwrap_or((Gender::Unknown, Number::Singular))
4322                        }
4323                    }
4324                    _ => (Gender::Unknown, Number::Singular),
4325                };
4326                let resolved = self.resolve_pronoun(gender, number)?;
4327                match resolved {
4328                    super::ResolvedPronoun::Variable(s) => Term::Variable(s),
4329                    super::ResolvedPronoun::Constant(s) => Term::Constant(s),
4330                }
4331            } else if self.check_content_word() || self.check_article() {
4332                let prep_obj = self.parse_noun_phrase(false)?;
4333                Term::Constant(prep_obj.noun)
4334            } else if self.check_number() {
4335                // "N unit NOUN" is a measure-premodified noun ("brew with 190
4336                // degree WATER") — ONE folded entity, not a measure with the
4337                // head stranded. A noun/ambiguous head after the unit signals
4338                // it; else the PP object is the bare measure ("sold for $105").
4339                let premodified = matches!(
4340                    self.tokens.get(self.current + 2).map(|t| &t.kind),
4341                    Some(TokenType::Noun(_)) | Some(TokenType::Ambiguous { .. })
4342                );
4343                if premodified {
4344                    let saved_ctx = self.nominal_np_context;
4345                    self.nominal_np_context = true;
4346                    let r = self.parse_noun_phrase(false);
4347                    self.nominal_np_context = saved_ctx;
4348                    Term::Constant(r?.noun)
4349                } else {
4350                    *self.parse_measure_phrase()?
4351                }
4352            } else if gap_object {
4353                // Preposition stranding: the object position was a wh-gap,
4354                // so the bare preposition is licensed ("Who did John talk to?").
4355                continue;
4356            } else if self.at_clause_boundary()
4357                && crate::lexicon::is_particle(&self.interner.resolve(prep_name).to_lowercase())
4358            {
4359                // A clause-final object-less PARTICLE preposition is an
4360                // intransitive directional ("walked in", "sat down") — a
4361                // lexically listed class; "of"/"to" cannot end a clause.
4362                let event_sym = self.get_event_var();
4363                pp_predicates.push(self.ctx.exprs.alloc(LogicExpr::Predicate {
4364                    name: prep_name,
4365                    args: self.ctx.terms.alloc_slice([Term::Variable(event_sym)]),
4366                    world: None,
4367                }));
4368                continue;
4369            } else {
4370                // A mid-clause preposition with no object is not a PP —
4371                // hand it back so the sentence-level parse reports it
4372                // instead of silently dropping it.
4373                self.current -= 1;
4374                break;
4375            };
4376
4377            if self.pp_attach_to_noun {
4378                if let Some(obj) = object_term {
4379                    let pp_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
4380                        name: prep_name,
4381                        args: self.ctx.terms.alloc_slice([obj, pp_obj_term]),
4382                        world: None,
4383                    });
4384                    pp_predicates.push(pp_pred);
4385                } else {
4386                    args.push(pp_obj_term);
4387                }
4388            } else {
4389                let event_sym = self.get_event_var();
4390                let pp_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
4391                    name: prep_name,
4392                    args: self
4393                        .ctx
4394                        .terms
4395                        .alloc_slice([Term::Variable(event_sym), pp_obj_term]),
4396                    world: None,
4397                });
4398                pp_predicates.push(pp_pred);
4399            }
4400        }
4401
4402        if self.check(&TokenType::That) || self.check(&TokenType::Who) {
4403            self.advance();
4404            let rel_var = self.next_var_name();
4405            let rel_pred = self.parse_relative_clause(rel_var)?;
4406            pp_predicates.push(rel_pred);
4407        }
4408
4409        // "X has Y as [its/his/her] ROLE" — a predicative secondary on the
4410        // object: Y fills ROLE for the subject ("the city has Al Acosta as its
4411        // mayor" → Have(City, Al_Acosta) ∧ Mayor(Al_Acosta)). The Have-link
4412        // already binds Y to the subject, so the possessive determiner is
4413        // redundant and dropped. "as" lexes as a Noun (function-word fallback),
4414        // hence the lexeme test; the noun-compound loop leaves it unbundled.
4415        if object_term.is_some()
4416            && matches!(self.peek().kind, TokenType::Noun(_))
4417            && self
4418                .interner
4419                .resolve(self.peek().lexeme)
4420                .eq_ignore_ascii_case("as")
4421        {
4422            self.advance(); // consume "as"
4423            if self.check_possessive_pronoun() {
4424                self.advance(); // consume "its" / "his" / "her"
4425            }
4426            if self.check_content_word() {
4427                as_role = Some(self.consume_content_word()?);
4428            }
4429        }
4430
4431        let mut modifiers = self.collect_adverbs();
4432
4433        let effective_time = self.pending_time.take().unwrap_or(verb_time);
4434        match effective_time {
4435            Time::Past => modifiers.push(self.interner.intern("Past")),
4436            Time::Future => modifiers.push(self.interner.intern("Future")),
4437            _ => {}
4438        }
4439
4440        if verb_aspect == Aspect::Progressive {
4441            modifiers.push(self.interner.intern("Progressive"));
4442        } else if verb_aspect == Aspect::Perfect {
4443            modifiers.push(self.interner.intern("Perfect"));
4444        }
4445
4446        let mut roles: Vec<(ThematicRole, Term<'a>)> = Vec::new();
4447
4448        // Check if verb is unaccusative (intransitive subject is Theme, not Agent)
4449        let verb_str = self.interner.resolve(verb).to_lowercase();
4450        let is_unaccusative = crate::lexicon::lookup_verb_db(&verb_str)
4451            .map(|meta| {
4452                meta.features
4453                    .contains(&crate::lexicon::Feature::Unaccusative)
4454            })
4455            .unwrap_or(false);
4456
4457        // Unaccusative verbs used intransitively: subject is Theme
4458        // E.g., "The alarm triggers" → Theme(e, Alarm), not Agent(e, Alarm)
4459        let has_object = object_term.is_some() || second_object_term.is_some();
4460        let subject_role = if is_unaccusative && !has_object {
4461            ThematicRole::Theme
4462        } else {
4463            ThematicRole::Agent
4464        };
4465
4466        roles.push((subject_role, subject_term));
4467        if let Some(second_obj) = second_object_term {
4468            if let Some(first_obj) = object_term {
4469                roles.push((ThematicRole::Recipient, first_obj));
4470            }
4471            roles.push((ThematicRole::Theme, second_obj));
4472        } else if let Some(obj) = object_term {
4473            roles.push((ThematicRole::Theme, obj));
4474        }
4475
4476        let event_var = self.get_event_var();
4477        let suppress_existential = self.drs.in_conditional_antecedent();
4478        if suppress_existential {
4479            let event_class = self.interner.intern("Event");
4480            self.drs.introduce_event_referent(event_var, event_class);
4481        }
4482        // Capture template for ellipsis reconstruction
4483        self.capture_event_template(verb, &roles, &modifiers);
4484
4485        let with_pps = self.event_with_conditions(
4486            NeoEventData {
4487                event_var,
4488                verb,
4489                roles: self.ctx.roles.alloc_slice(roles),
4490                modifiers: self.ctx.syms.alloc_slice(modifiers),
4491                suppress_existential,
4492                world: None,
4493            },
4494            pp_predicates,
4495        );
4496
4497        // Include PPs attached to object NP (for NP-attachment mode)
4498        // These have _PP_SELF_ placeholder that needs to be replaced with the object term
4499        let with_object_pps = if object_pps.is_empty() {
4500            with_pps
4501        } else if let Some(obj_term) = object_term {
4502            let mut combined = with_pps;
4503            for pp in object_pps {
4504                // Rebind the `_PP_SELF_` gap to the object term, recursing
4505                // through connectives / quantifiers / events so a reduced
4506                // relative restrictor ("the friend Simon went WITH" →
4507                // ∃e(Go(e) ∧ Agent(e,Simon) ∧ With(e, _PP_SELF_))) binds its
4508                // stranded-preposition gap to the head, not just a flat PP.
4509                let substituted = self.substitute_pp_self_term(pp, obj_term);
4510                combined = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
4511                    left: combined,
4512                    op: TokenType::And,
4513                    right: substituted,
4514                });
4515            }
4516            combined
4517        } else {
4518            with_pps
4519        };
4520
4521        // Predicate the definite/constant object's adjectives of it ("ate the
4522        // RED apple" → Red(Apple)); like the PPs above, dropping them loses a
4523        // constraint.
4524        let with_object_pps = if object_adjectives.is_empty() {
4525            with_object_pps
4526        } else if let Some(obj_term) = object_term {
4527            let mut combined = with_object_pps;
4528            for &adj in object_adjectives {
4529                let adj_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
4530                    name: adj,
4531                    args: self.ctx.terms.alloc_slice([obj_term]),
4532                    world: None,
4533                });
4534                combined = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
4535                    left: combined,
4536                    op: TokenType::And,
4537                    right: adj_pred,
4538                });
4539            }
4540            combined
4541        } else {
4542            with_object_pps
4543        };
4544
4545        // Apply aspectual operators based on verb class
4546        let with_aspect = if verb_aspect == Aspect::Simple && effective_time == Time::Present {
4547            // Non-state verbs in simple present get Habitual reading
4548            if !verb_class.is_stative() {
4549                self.ctx.exprs.alloc(LogicExpr::Aspectual {
4550                    operator: AspectOperator::Habitual,
4551                    body: with_object_pps,
4552                })
4553            } else {
4554                with_object_pps
4555            }
4556        } else if verb_aspect == Aspect::Progressive {
4557            // Semelfactive + Progressive → Iterative
4558            if verb_class == crate::lexicon::VerbClass::Semelfactive {
4559                self.ctx.exprs.alloc(LogicExpr::Aspectual {
4560                    operator: AspectOperator::Iterative,
4561                    body: with_object_pps,
4562                })
4563            } else {
4564                with_object_pps
4565            }
4566        } else {
4567            with_object_pps
4568        };
4569
4570        // Conjoin the predicative-secondary role ("as its mayor" → Mayor(Y)).
4571        let with_aspect = if let (Some(role), Some(obj)) = (as_role, object_term) {
4572            let role_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
4573                name: role,
4574                args: self.ctx.terms.alloc_slice([obj]),
4575                world: None,
4576            });
4577            self.ctx.exprs.alloc(LogicExpr::BinaryOp {
4578                left: with_aspect,
4579                op: TokenType::And,
4580                right: role_pred,
4581            })
4582        } else {
4583            with_aspect
4584        };
4585
4586        Ok(with_aspect)
4587    }
4588}
4589
4590impl<'a, 'ctx, 'int> LogicVerbParsing<'a, 'ctx, 'int> for Parser<'a, 'ctx, 'int> {
4591    fn parse_predicate_with_subject(
4592        &mut self,
4593        subject_symbol: Symbol,
4594    ) -> ParseResult<&'a LogicExpr<'a>> {
4595        let result = self.parse_predicate_impl(subject_symbol, false)?;
4596        Ok(self.try_wrap_bounded_delay(result))
4597    }
4598
4599    fn parse_predicate_with_subject_as_var(
4600        &mut self,
4601        subject_symbol: Symbol,
4602    ) -> ParseResult<&'a LogicExpr<'a>> {
4603        let result = self.parse_predicate_impl(subject_symbol, true)?;
4604        Ok(self.try_wrap_bounded_delay(result))
4605    }
4606
4607    fn try_parse_plural_subject(
4608        &mut self,
4609        first_subject: &NounPhrase<'a>,
4610    ) -> Result<Option<&'a LogicExpr<'a>>, ParseError> {
4611        let saved_pos = self.backtrack_point();
4612
4613        // Consume the 'and' we already peeked
4614        self.advance();
4615
4616        if !self.check_content_word() {
4617            self.backtrack_to(&saved_pos);
4618            return Ok(None);
4619        }
4620
4621        // Collect all subjects: "John and Mary and Sue"
4622        let mut subjects: Vec<Symbol> = vec![first_subject.noun];
4623
4624        loop {
4625            if !self.check_content_word() {
4626                break;
4627            }
4628            let next_subject = match self.parse_noun_phrase(true) {
4629                Ok(np) => np,
4630                Err(_) => {
4631                    self.backtrack_to(&saved_pos);
4632                    return Ok(None);
4633                }
4634            };
4635            subjects.push(next_subject.noun);
4636
4637            if self.check(&TokenType::And) {
4638                self.advance();
4639            } else {
4640                break;
4641            }
4642        }
4643
4644        // Check for copula (is/are/was/were) with predicate nominative
4645        // "Both Socrates and Plato are men" -> M(s) ∧ M(p)
4646        if self.check(&TokenType::Is)
4647            || self.check(&TokenType::Are)
4648            || self.check(&TokenType::Was)
4649            || self.check(&TokenType::Were)
4650        {
4651            let copula_time = if self.check(&TokenType::Was) || self.check(&TokenType::Were) {
4652                Time::Past
4653            } else {
4654                Time::Present
4655            };
4656            self.advance(); // consume the copula
4657
4658            // Check for negation: "are not valid", "are not both valid"
4659            let is_negated = self.check(&TokenType::Not);
4660            if is_negated {
4661                self.advance(); // consume "not"
4662            }
4663
4664            // Check for "both" modifier: "are not both valid"
4665            // "both" scopes negation over the conjunction: ¬(P(A) ∧ P(B))
4666            // Without "both": negation distributes: ¬P(A) ∧ ¬P(B)
4667            let has_both = self.check(&TokenType::Both);
4668            if has_both {
4669                self.advance(); // consume "both"
4670            }
4671
4672            // Parse the predicate (e.g., "men" in "are men", "valid" in "are valid")
4673            if !self.check_content_word() && !self.check_article() {
4674                self.backtrack_to(&saved_pos);
4675                return Ok(None);
4676            }
4677
4678            let predicate_np = match self.parse_noun_phrase(false) {
4679                Ok(np) => np,
4680                Err(_) => {
4681                    self.backtrack_to(&saved_pos);
4682                    return Ok(None);
4683                }
4684            };
4685            let predicate = predicate_np.noun;
4686
4687            // "A and B are DIFFERENT people" — the adjective "different" asserts
4688            // the members are pairwise DISTINCT (the puzzle solver's AllDifferent
4689            // constraint). Dropping it loses the constraint, so it is kept as
4690            // ¬(si = sj) below; mirrors the comma-list subject path.
4691            let is_different = predicate_np
4692                .adjectives
4693                .iter()
4694                .any(|a| self.interner.resolve(*a).eq_ignore_ascii_case("different"));
4695
4696            // A category DECLARATION ("Bill, Lillie, … are four different friends.",
4697            // "2001, … are four different years.") records item→category in the
4698            // shared discourse DRS, so a later definite LABEL ("the 2003 holiday",
4699            // "the Florida trip") can recover the category and un-fuse to the same
4700            // relation the prepositional-phrase form produces. The predicate
4701            // nominal is the category noun; each coordinated subject is an item of
4702            // that category.
4703            for subj in &subjects {
4704                self.drs.register_item_category(*subj, predicate);
4705            }
4706
4707            // Build distributed predicate: P(s1) ∧ P(s2) ∧ ...
4708            let mut conjuncts: Vec<&'a LogicExpr<'a>> = Vec::new();
4709            for subj in &subjects {
4710                let pred_expr = self.ctx.exprs.alloc(LogicExpr::Predicate {
4711                    name: predicate,
4712                    args: self.ctx.terms.alloc_slice([Term::Constant(*subj)]),
4713                    world: None,
4714                });
4715                conjuncts.push(pred_expr);
4716            }
4717            if is_different {
4718                for i in 0..subjects.len() {
4719                    for j in (i + 1)..subjects.len() {
4720                        let eq = self.ctx.exprs.alloc(LogicExpr::Identity {
4721                            left: self.ctx.terms.alloc(Term::Constant(subjects[i])),
4722                            right: self.ctx.terms.alloc(Term::Constant(subjects[j])),
4723                        });
4724                        conjuncts.push(self.ctx.exprs.alloc(LogicExpr::UnaryOp {
4725                            op: TokenType::Not,
4726                            operand: eq,
4727                        }));
4728                    }
4729                }
4730            }
4731
4732            if is_negated && !has_both {
4733                // "are not valid" → ¬P(s1) ∧ ¬P(s2) (negation distributes)
4734                for conjunct in &mut conjuncts {
4735                    *conjunct = self.ctx.exprs.alloc(LogicExpr::UnaryOp {
4736                        op: TokenType::Not,
4737                        operand: *conjunct,
4738                    });
4739                }
4740            }
4741
4742            // Fold conjuncts into binary conjunction tree
4743            let mut result = conjuncts[0];
4744            for conjunct in &conjuncts[1..] {
4745                result = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
4746                    left: result,
4747                    op: TokenType::And,
4748                    right: *conjunct,
4749                });
4750            }
4751
4752            // "are not both valid" → ¬(P(s1) ∧ P(s2)) (negation over conjunction)
4753            if is_negated && has_both {
4754                result = self.ctx.exprs.alloc(LogicExpr::UnaryOp {
4755                    op: TokenType::Not,
4756                    operand: result,
4757                });
4758            }
4759
4760            // Apply temporal modifier for past tense
4761            let with_time = match copula_time {
4762                Time::Past => self.ctx.exprs.alloc(LogicExpr::Temporal {
4763                    operator: TemporalOperator::Past,
4764                    body: result,
4765                }),
4766                _ => result,
4767            };
4768
4769            return Ok(Some(with_time));
4770        }
4771
4772        if !self.check_verb() {
4773            self.backtrack_to(&saved_pos);
4774            return Ok(None);
4775        }
4776
4777        // Coordinated subjects registered in DRS via introduce_referent
4778
4779        let (verb, verb_time, _verb_aspect, _) = self.consume_verb_with_metadata();
4780
4781        // Check for reciprocal: "John and Mary kicked each other"
4782        if self.check(&TokenType::Reciprocal) {
4783            self.advance();
4784            if subjects.len() != 2 {
4785                self.backtrack_to(&saved_pos);
4786                return Ok(None);
4787            }
4788            let pred1 = self.ctx.exprs.alloc(LogicExpr::Predicate {
4789                name: verb,
4790                args: self
4791                    .ctx
4792                    .terms
4793                    .alloc_slice([Term::Constant(subjects[0]), Term::Constant(subjects[1])]),
4794                world: None,
4795            });
4796            let pred2 = self.ctx.exprs.alloc(LogicExpr::Predicate {
4797                name: verb,
4798                args: self
4799                    .ctx
4800                    .terms
4801                    .alloc_slice([Term::Constant(subjects[1]), Term::Constant(subjects[0])]),
4802                world: None,
4803            });
4804            let expr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
4805                left: pred1,
4806                op: TokenType::And,
4807                right: pred2,
4808            });
4809
4810            let with_time = match verb_time {
4811                Time::Past => self.ctx.exprs.alloc(LogicExpr::Temporal {
4812                    operator: TemporalOperator::Past,
4813                    body: expr,
4814                }),
4815                Time::Future => self.ctx.exprs.alloc(LogicExpr::Temporal {
4816                    operator: TemporalOperator::Future,
4817                    body: expr,
4818                }),
4819                _ => expr,
4820            };
4821            return Ok(Some(with_time));
4822        }
4823
4824        // Check for objects (for transitive verbs with "respectively")
4825        let mut objects: Vec<Symbol> = Vec::new();
4826        if self.check_content_word() || self.check_article() {
4827            // Parse first object
4828            let first_obj = match self.parse_noun_phrase(false) {
4829                Ok(np) => np,
4830                Err(_) => {
4831                    // No objects, continue with intransitive
4832                    return Ok(Some(self.build_group_predicate(&subjects, verb, verb_time)));
4833                }
4834            };
4835            objects.push(first_obj.noun);
4836
4837            // Parse additional objects: "Tom and Jerry and Bob"
4838            while self.check(&TokenType::And) {
4839                self.advance();
4840                if self.check_content_word() || self.check_article() {
4841                    let next_obj = match self.parse_noun_phrase(false) {
4842                        Ok(np) => np,
4843                        Err(_) => break,
4844                    };
4845                    objects.push(next_obj.noun);
4846                } else {
4847                    break;
4848                }
4849            }
4850        }
4851
4852        // Check for "respectively" - triggers pairwise interpretation
4853        // Ditransitive pairing ("gave books TO TOM AND JERRY respectively"):
4854        // the recipients, not the shared theme, line up with the subjects.
4855        let mut recipients: Vec<Symbol> = Vec::new();
4856        let respectively_ahead = {
4857            let mut i = self.current;
4858            let mut found = false;
4859            while i < self.tokens.len()
4860                && !matches!(self.tokens[i].kind, TokenType::Period | TokenType::EOF)
4861            {
4862                if matches!(self.tokens[i].kind, TokenType::Respectively) {
4863                    found = true;
4864                    break;
4865                }
4866                i += 1;
4867            }
4868            found
4869        };
4870        if respectively_ahead && self.check_to_marker() {
4871            self.advance(); // to
4872            loop {
4873                let r_np = self.parse_noun_phrase(false)?;
4874                recipients.push(r_np.noun);
4875                if self.check(&TokenType::And) {
4876                    self.advance();
4877                } else {
4878                    break;
4879                }
4880            }
4881        }
4882
4883        if self.check(&TokenType::Respectively) {
4884            let respectively_span = self.peek().span;
4885            self.advance(); // consume "respectively"
4886
4887            let pair_targets: &[Symbol] = if recipients.is_empty() {
4888                &objects
4889            } else {
4890                &recipients
4891            };
4892            if subjects.len() != pair_targets.len() {
4893                return Err(ParseError {
4894                    kind: ParseErrorKind::RespectivelyLengthMismatch {
4895                        subject_count: subjects.len(),
4896                        object_count: pair_targets.len(),
4897                    },
4898                    span: respectively_span,
4899                });
4900            }
4901
4902            // Build pairwise predicates: See(J,T) ∧ See(M,J) ∧ ...; with
4903            // recipients, the theme is shared: Give(J,Books,T) ∧ Give(M,Books,J).
4904            let mut conjuncts: Vec<&'a LogicExpr<'a>> = Vec::new();
4905            let suppress_existential = self.drs.in_conditional_antecedent();
4906            for (subj, target) in subjects.iter().zip(pair_targets.iter()) {
4907                let event_var = self.get_event_var();
4908                let roles = if recipients.is_empty() {
4909                    vec![
4910                        (ThematicRole::Agent, Term::Constant(*subj)),
4911                        (ThematicRole::Theme, Term::Constant(*target)),
4912                    ]
4913                } else {
4914                    let mut r = vec![(ThematicRole::Agent, Term::Constant(*subj))];
4915                    if let Some(theme) = objects.first() {
4916                        r.push((ThematicRole::Theme, Term::Constant(*theme)));
4917                    }
4918                    r.push((ThematicRole::Recipient, Term::Constant(*target)));
4919                    r
4920                };
4921                let neo_event = self
4922                    .ctx
4923                    .exprs
4924                    .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
4925                        event_var,
4926                        verb,
4927                        roles: self.ctx.roles.alloc_slice(roles),
4928                        modifiers: self.ctx.syms.alloc_slice(vec![]),
4929                        suppress_existential,
4930                        world: None,
4931                    })));
4932                conjuncts.push(neo_event);
4933            }
4934
4935            // Fold conjuncts into binary conjunction tree
4936            let mut result = conjuncts[0];
4937            for conjunct in &conjuncts[1..] {
4938                result = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
4939                    left: result,
4940                    op: TokenType::And,
4941                    right: *conjunct,
4942                });
4943            }
4944
4945            // Apply temporal modifier
4946            let with_time = match verb_time {
4947                Time::Past => self.ctx.exprs.alloc(LogicExpr::Temporal {
4948                    operator: TemporalOperator::Past,
4949                    body: result,
4950                }),
4951                Time::Future => self.ctx.exprs.alloc(LogicExpr::Temporal {
4952                    operator: TemporalOperator::Future,
4953                    body: result,
4954                }),
4955                _ => result,
4956            };
4957
4958            return Ok(Some(with_time));
4959        }
4960
4961        // No "respectively" - use group semantics
4962        if objects.is_empty() {
4963            // Intransitive: group subject
4964            Ok(Some(self.build_group_predicate(&subjects, verb, verb_time)))
4965        } else {
4966            // Transitive without "respectively": group subject, group object
4967            Ok(Some(self.build_group_transitive(
4968                &subjects, &objects, verb, verb_time,
4969            )))
4970        }
4971    }
4972
4973    /// Build a group predicate for intransitive verbs
4974    fn build_group_predicate(
4975        &mut self,
4976        subjects: &[Symbol],
4977        verb: Symbol,
4978        verb_time: Time,
4979    ) -> &'a LogicExpr<'a> {
4980        let group_members: Vec<Term<'a>> = subjects.iter().map(|s| Term::Constant(*s)).collect();
4981        let group_members_slice = self.ctx.terms.alloc_slice(group_members);
4982
4983        let expr = self.ctx.exprs.alloc(LogicExpr::Predicate {
4984            name: verb,
4985            args: self
4986                .ctx
4987                .terms
4988                .alloc_slice([Term::Group(group_members_slice)]),
4989            world: None,
4990        });
4991
4992        match verb_time {
4993            Time::Past => self.ctx.exprs.alloc(LogicExpr::Temporal {
4994                operator: TemporalOperator::Past,
4995                body: expr,
4996            }),
4997            Time::Future => self.ctx.exprs.alloc(LogicExpr::Temporal {
4998                operator: TemporalOperator::Future,
4999                body: expr,
5000            }),
5001            _ => expr,
5002        }
5003    }
5004
5005    /// Build a transitive predicate with group subject and group object
5006    fn build_group_transitive(
5007        &mut self,
5008        subjects: &[Symbol],
5009        objects: &[Symbol],
5010        verb: Symbol,
5011        verb_time: Time,
5012    ) -> &'a LogicExpr<'a> {
5013        let subj_members: Vec<Term<'a>> = subjects.iter().map(|s| Term::Constant(*s)).collect();
5014        let obj_members: Vec<Term<'a>> = objects.iter().map(|o| Term::Constant(*o)).collect();
5015
5016        let subj_group = Term::Group(self.ctx.terms.alloc_slice(subj_members));
5017        let obj_group = Term::Group(self.ctx.terms.alloc_slice(obj_members));
5018
5019        let expr = self.ctx.exprs.alloc(LogicExpr::Predicate {
5020            name: verb,
5021            args: self.ctx.terms.alloc_slice([subj_group, obj_group]),
5022            world: None,
5023        });
5024
5025        match verb_time {
5026            Time::Past => self.ctx.exprs.alloc(LogicExpr::Temporal {
5027                operator: TemporalOperator::Past,
5028                body: expr,
5029            }),
5030            Time::Future => self.ctx.exprs.alloc(LogicExpr::Temporal {
5031                operator: TemporalOperator::Future,
5032                body: expr,
5033            }),
5034            _ => expr,
5035        }
5036    }
5037
5038    fn parse_control_structure(
5039        &mut self,
5040        subject: &NounPhrase<'a>,
5041        verb: Symbol,
5042        verb_time: Time,
5043    ) -> ParseResult<&'a LogicExpr<'a>> {
5044        let subject_sym = subject.noun;
5045        let verb_str = self.interner.resolve(verb);
5046
5047        if Lexer::is_raising_verb(verb_str) {
5048            if !self.check_to() {
5049                return Ok(self.ctx.exprs.alloc(LogicExpr::Predicate {
5050                    name: verb,
5051                    args: self.ctx.terms.alloc_slice([Term::Constant(subject_sym)]),
5052                    world: None,
5053                }));
5054            }
5055            self.advance();
5056
5057            if !self.check_verb() {
5058                return Ok(self.ctx.exprs.alloc(LogicExpr::Predicate {
5059                    name: verb,
5060                    args: self.ctx.terms.alloc_slice([Term::Constant(subject_sym)]),
5061                    world: None,
5062                }));
5063            }
5064
5065            let inf_verb = self.consume_verb();
5066
5067            let embedded = if self.is_control_verb(inf_verb) {
5068                let raised_np = NounPhrase {
5069                    noun: subject_sym,
5070                    definiteness: None,
5071                    adjectives: &[],
5072                    possessor: None,
5073                    pps: &[],
5074                    superlative: None,
5075                };
5076                self.parse_control_structure(&raised_np, inf_verb, Time::None)?
5077            } else {
5078                self.ctx.exprs.alloc(LogicExpr::Predicate {
5079                    name: inf_verb,
5080                    args: self.ctx.terms.alloc_slice([Term::Constant(subject_sym)]),
5081                    world: None,
5082                })
5083            };
5084
5085            let result = self.ctx.exprs.alloc(LogicExpr::Scopal {
5086                operator: verb,
5087                body: embedded,
5088            });
5089
5090            return Ok(match verb_time {
5091                Time::Past => self.ctx.exprs.alloc(LogicExpr::Temporal {
5092                    operator: TemporalOperator::Past,
5093                    body: result,
5094                }),
5095                Time::Future => self.ctx.exprs.alloc(LogicExpr::Temporal {
5096                    operator: TemporalOperator::Future,
5097                    body: result,
5098                }),
5099                _ => result,
5100            });
5101        }
5102
5103        let is_object_control = Lexer::is_object_control_verb(self.interner.resolve(verb));
5104        let (object_term, pro_controller_sym) = if self.check_to() {
5105            (None, subject_sym)
5106        } else if self.check_content_word() {
5107            let object_np = self.parse_noun_phrase(false)?;
5108            let obj_sym = object_np.noun;
5109
5110            let controller = if is_object_control {
5111                obj_sym
5112            } else {
5113                subject_sym
5114            };
5115            (
5116                Some(self.ctx.terms.alloc(Term::Constant(obj_sym))),
5117                controller,
5118            )
5119        } else {
5120            (None, subject_sym)
5121        };
5122
5123        if !self.check_to() {
5124            return Ok(self.ctx.exprs.alloc(LogicExpr::Predicate {
5125                name: verb,
5126                args: match object_term {
5127                    Some(obj) => self.ctx.terms.alloc_slice([
5128                        Term::Constant(subject_sym),
5129                        Term::Constant(match obj {
5130                            Term::Constant(s) => *s,
5131                            _ => subject_sym,
5132                        }),
5133                    ]),
5134                    None => self.ctx.terms.alloc_slice([Term::Constant(subject_sym)]),
5135                },
5136                world: None,
5137            }));
5138        }
5139        self.advance();
5140
5141        if !self.check_verb() {
5142            return Ok(self.ctx.exprs.alloc(LogicExpr::Predicate {
5143                name: verb,
5144                args: self.ctx.terms.alloc_slice([Term::Constant(subject_sym)]),
5145                world: None,
5146            }));
5147        }
5148
5149        let inf_verb = self.consume_verb();
5150        let inf_verb_str = self.interner.resolve(inf_verb).to_lowercase();
5151
5152        let infinitive = if inf_verb_str == "be" && self.check_verb() {
5153            let passive_verb = self.consume_verb();
5154            // An agent by-phrase fills the first argument slot, matching the
5155            // finite passive ("was seen by the people" → See(People, s)).
5156            let mut passive_args = vec![Term::Constant(pro_controller_sym)];
5157            // A DESCRIPTIVE control-passive by-agent ("…to be fed by the old man")
5158            // becomes its own restrictor-carrying entity scoping the relation; a
5159            // bare one keeps the constant form.
5160            let mut agent_restr: Option<(Symbol, &'a LogicExpr<'a>)> = None;
5161            if self.check_preposition_is("by")
5162                && self.tokens.get(self.current + 1).map_or(false, |t| {
5163                    matches!(
5164                        t.kind,
5165                        TokenType::ProperName(_) | TokenType::Noun(_) | TokenType::Article(_)
5166                    )
5167                })
5168            {
5169                self.advance(); // by
5170                let agent_np = self.parse_noun_phrase(false)?;
5171                let (agent_term, restr) = self.possessor_entity(&agent_np);
5172                agent_restr = restr;
5173                passive_args.insert(0, agent_term);
5174            }
5175            let passive_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
5176                name: passive_verb,
5177                args: self.ctx.terms.alloc_slice(passive_args),
5178                world: None,
5179            });
5180            let passive_pred = self.wrap_in_possessor_entity(agent_restr, passive_pred);
5181            self.ctx
5182                .voice(crate::ast::VoiceOperator::Passive, passive_pred)
5183        } else if self.is_control_verb(inf_verb) {
5184            let controller_np = NounPhrase {
5185                noun: pro_controller_sym,
5186                definiteness: None,
5187                adjectives: &[],
5188                possessor: None,
5189                pps: &[],
5190                superlative: None,
5191            };
5192            self.parse_control_structure(&controller_np, inf_verb, Time::None)?
5193        } else {
5194            self.ctx.exprs.alloc(LogicExpr::Predicate {
5195                name: inf_verb,
5196                args: self
5197                    .ctx
5198                    .terms
5199                    .alloc_slice([Term::Constant(pro_controller_sym)]),
5200                world: None,
5201            })
5202        };
5203
5204        let control = self.ctx.exprs.alloc(LogicExpr::Control {
5205            verb,
5206            subject: self.ctx.terms.alloc(Term::Constant(subject_sym)),
5207            object: object_term,
5208            infinitive,
5209        });
5210
5211        Ok(match verb_time {
5212            Time::Past => self.ctx.exprs.alloc(LogicExpr::Temporal {
5213                operator: TemporalOperator::Past,
5214                body: control,
5215            }),
5216            Time::Future => self.ctx.exprs.alloc(LogicExpr::Temporal {
5217                operator: TemporalOperator::Future,
5218                body: control,
5219            }),
5220            _ => control,
5221        })
5222    }
5223
5224    fn is_control_verb(&self, verb: Symbol) -> bool {
5225        let lemma = self.interner.resolve(verb);
5226        Lexer::is_subject_control_verb(lemma)
5227            || Lexer::is_object_control_verb(lemma)
5228            || Lexer::is_raising_verb(lemma)
5229    }
5230}