Skip to main content

logicaffeine_language/parser/
pragmatics.rs

1//! Pragmatic inference and focus-sensitive parsing.
2//!
3//! This module handles linguistic phenomena that go beyond pure syntax/semantics:
4//!
5//! - **Focus particles**: "only", "even", "also" with alternative semantics
6//! - **Presupposition triggers**: "stop", "continue", "too"
7//! - **Measure phrases**: Dimensional expressions with units
8//! - **Comparatives**: "taller than", "as tall as", degree semantics
9//! - **Superlatives**: "the tallest", unique maximal individuals
10//! - **Scopal adverbs**: "always", "never", "usually"
11//!
12//! Focus is represented using the `LogicExpr::Focus` variant with an alternatives
13//! set derived from the focus domain.
14
15use super::clause::ClauseParsing;
16use super::noun::NounParsing;
17use super::quantifier::QuantifierParsing;
18use super::{ParseResult, Parser};
19use crate::ast::{LogicExpr, NounPhrase, NumberKind, QuantifierKind, TemporalOperator, Term};
20use crate::error::{ParseError, ParseErrorKind};
21use crate::lexicon::{self, Time};
22use crate::token::{MeasureKind, PresupKind, TokenType};
23
24/// Trait for parsing pragmatic and focus-sensitive constructions.
25///
26/// Provides methods for parsing linguistic phenomena that go beyond pure
27/// syntax/semantics, including focus particles, presupposition triggers,
28/// measure phrases, degree expressions (comparatives/superlatives), and
29/// scopal adverbs.
30///
31/// Focus is represented using alternative semantics, where the focused
32/// element evokes a set of alternatives. Presuppositions project through
33/// various operators and represent background entailments.
34pub trait PragmaticsParsing<'a, 'ctx, 'int> {
35    /// Parses a focus particle construction: "only John runs", "even Mary left".
36    ///
37    /// Focus particles like "only", "even", and "also" introduce alternative
38    /// semantics. The focused element is contrasted with a contextually
39    /// determined set of alternatives.
40    ///
41    /// Returns a [`LogicExpr::Focus`] with the focus kind, focused element,
42    /// and the scope predicate.
43    fn parse_focus(&mut self) -> ParseResult<&'a LogicExpr<'a>>;
44
45    /// Parses a measure construction: "much water is cold", "little food arrived".
46    ///
47    /// Measure expressions quantify over amounts using "much", "little", etc.
48    /// The result is an existentially quantified formula binding the measured
49    /// entity with a measure predicate.
50    fn parse_measure(&mut self) -> ParseResult<&'a LogicExpr<'a>>;
51
52    /// Parses a presupposition-triggering verb: "stopped running", "regrets leaving".
53    ///
54    /// Presupposition triggers introduce background entailments that project
55    /// through negation and other operators:
56    ///
57    /// - "stop P" presupposes: previously P; asserts: now ¬P
58    /// - "start P" presupposes: previously ¬P; asserts: now P
59    /// - "regret P" presupposes: P happened; asserts: subject regrets it
60    /// - "continue P" presupposes: was P; asserts: still P
61    ///
62    /// Returns a [`LogicExpr::Presupposition`] separating assertion from presupposition.
63    fn parse_presupposition(
64        &mut self,
65        subject: &NounPhrase<'a>,
66        presup_kind: PresupKind,
67        negated: bool,
68    ) -> ParseResult<&'a LogicExpr<'a>>;
69
70    /// Term-parametric form of [`Self::parse_presupposition`] — the subject is a
71    /// TERM (constant or a relativized variable) so the same presupposition
72    /// grammar composes over a relative-clause subject ("the person who won
73    /// started skydiving 2 years after …").
74    fn parse_presupposition_for_term(
75        &mut self,
76        subject_term: Term<'a>,
77        presup_kind: PresupKind,
78        negated: bool,
79    ) -> ParseResult<&'a LogicExpr<'a>>;
80
81    /// Parses a simple predicate for a given subject noun phrase.
82    ///
83    /// Handles verb phrases with optional objects and focus-marked objects
84    /// like "eats only rice". Used as a helper for focus and other pragmatic
85    /// constructions.
86    fn parse_predicate_for_subject(
87        &mut self,
88        subject: &NounPhrase<'a>,
89    ) -> ParseResult<&'a LogicExpr<'a>>;
90
91    /// Parses a scopal adverb construction: "always runs", "never sleeps".
92    ///
93    /// Scopal adverbs like "always", "never", "usually", "sometimes" quantify
94    /// over times, events, or situations. They create a [`LogicExpr::Scopal`]
95    /// operator that scopes over the verb predicate.
96    fn parse_scopal_adverb(&mut self, subject: &NounPhrase<'a>) -> ParseResult<&'a LogicExpr<'a>>;
97
98    /// Parses a superlative construction: "is the tallest student".
99    ///
100    /// Superlatives identify the unique maximal individual along a gradable
101    /// dimension within a comparison class. Returns a [`LogicExpr::Superlative`]
102    /// with the adjective, subject, and domain restrictor.
103    fn parse_superlative(&mut self, subject: &NounPhrase<'a>) -> ParseResult<&'a LogicExpr<'a>>;
104
105    /// Parses a comparative construction: "is taller than Mary", "is greater than 0".
106    ///
107    /// Comparatives establish an ordering relation along a gradable dimension.
108    /// Supports both NP comparisons ("taller than Mary") and numeric comparisons
109    /// ("greater than 0"). The optional `difference` parameter handles differential
110    /// comparatives like "3 inches taller".
111    ///
112    /// Returns a [`LogicExpr::Comparative`] with adjective, subject, and object.
113    fn parse_comparative(
114        &mut self,
115        subject: &NounPhrase<'a>,
116        copula_time: Time,
117        difference: Option<&'a Term<'a>>,
118    ) -> ParseResult<&'a LogicExpr<'a>>;
119
120    /// Parses the equative "X is as ADJ as Y" → an at-least (`≥`) comparison.
121    fn parse_equative(&mut self, subject: &NounPhrase<'a>) -> ParseResult<&'a LogicExpr<'a>>;
122
123    /// Checks if the current token is a numeric literal.
124    ///
125    /// Used to distinguish numeric comparisons ("greater than 0") from
126    /// entity comparisons ("taller than John").
127    fn check_number(&self) -> bool;
128
129    /// Parses a measure phrase: "5 meters", "100 kilograms".
130    ///
131    /// Measure phrases combine a numeric value with an optional unit.
132    /// The unit is looked up in the lexicon to determine its dimension
133    /// (length, mass, time, etc.).
134    ///
135    /// Returns a [`Term::Value`] with the parsed number, unit, and dimension.
136    fn parse_measure_phrase(&mut self) -> ParseResult<&'a Term<'a>>;
137
138    /// Recognises a digit-led COUNTING noun phrase in object position —
139    /// `Number (adjective)+ Noun` ("6 brown manatees", "49 previous jumps") —
140    /// and returns its integer count.
141    ///
142    /// The discriminator is the intervening adjective. A measure phrase is
143    /// `Number Unit` with no adjective ("190 points", "385 degrees"), so a bare
144    /// `Number Noun` stays a measure (the count and noun are preserved in the
145    /// [`Term::Value`] — no meaning loss, no regression). Only when an adjective
146    /// sits between the number and the head noun is the phrase unambiguously a
147    /// counting NP, which the caller routes through the canonical
148    /// cardinal-quantified-object machinery as `∃=n y(Noun(y) ∧ Adj(y) ∧ …)`
149    /// rather than mis-reading the adjective as a measure unit.
150    fn counting_np_lookahead(&self) -> Option<u32>;
151}
152
153impl<'a, 'ctx, 'int> PragmaticsParsing<'a, 'ctx, 'int> for Parser<'a, 'ctx, 'int> {
154    fn parse_focus(&mut self) -> ParseResult<&'a LogicExpr<'a>> {
155        let kind = if let TokenType::Focus(k) = self.advance().kind {
156            k
157        } else {
158            return Err(ParseError {
159                kind: ParseErrorKind::ExpectedFocusParticle,
160                span: self.current_span(),
161            });
162        };
163
164        if self.check_quantifier() {
165            self.advance();
166            let quantified = self.parse_quantified()?;
167            let focus_var = self.interner.intern("focus");
168            let focused = self.ctx.terms.alloc(Term::Variable(focus_var));
169            return Ok(self.ctx.exprs.alloc(LogicExpr::Focus {
170                kind,
171                focused,
172                scope: quantified,
173            }));
174        }
175
176        let focused_np = self.parse_noun_phrase(true)?;
177        let focused = self.ctx.terms.alloc(Term::Constant(focused_np.noun));
178
179        let scope = self.parse_predicate_for_subject(&focused_np)?;
180
181        Ok(self.ctx.exprs.alloc(LogicExpr::Focus {
182            kind,
183            focused,
184            scope,
185        }))
186    }
187
188    fn parse_measure(&mut self) -> ParseResult<&'a LogicExpr<'a>> {
189        let kind = if let TokenType::Measure(k) = self.advance().kind {
190            k
191        } else {
192            return Err(ParseError {
193                kind: ParseErrorKind::UnexpectedToken {
194                    expected: TokenType::Measure(MeasureKind::Much),
195                    found: self.peek().kind.clone(),
196                },
197                span: self.current_span(),
198            });
199        };
200
201        let np = self.parse_noun_phrase(true)?;
202        let var = self.next_var_name();
203
204        let noun_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
205            name: np.noun,
206            args: self.ctx.terms.alloc_slice([Term::Variable(var)]),
207            world: None,
208        });
209
210        let measure_sym = self.interner.intern("Measure");
211        let kind_sym = self.interner.intern(match kind {
212            MeasureKind::Much => "Much",
213            MeasureKind::Little => "Little",
214        });
215        let measure_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
216            name: measure_sym,
217            args: self
218                .ctx
219                .terms
220                .alloc_slice([Term::Variable(var), Term::Constant(kind_sym)]),
221            world: None,
222        });
223
224        let (pred_expr, verb_time) = if self.check(&TokenType::Is) {
225            let copula_time = if let TokenType::Is = self.advance().kind {
226                Time::Present
227            } else {
228                Time::Present
229            };
230
231            // Check for comparative: "is colder than"
232            if self.check_comparative() {
233                let subj_np = NounPhrase {
234                    noun: np.noun,
235                    definiteness: None,
236                    adjectives: &[],
237                    possessor: None,
238                    pps: &[],
239                    superlative: None,
240                };
241                let comp_expr = self.parse_comparative(&subj_np, copula_time, None)?;
242
243                let combined = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
244                    left: noun_pred,
245                    op: TokenType::And,
246                    right: self.ctx.exprs.alloc(LogicExpr::BinaryOp {
247                        left: measure_pred,
248                        op: TokenType::And,
249                        right: comp_expr,
250                    }),
251                });
252
253                return Ok(self.ctx.exprs.alloc(LogicExpr::Quantifier {
254                    kind: QuantifierKind::Existential,
255                    variable: var,
256                    body: combined,
257                    island_id: self.current_island,
258                }));
259            }
260
261            let adj = self.consume_content_word()?;
262            let adj_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
263                name: adj,
264                args: self.ctx.terms.alloc_slice([Term::Variable(var)]),
265                world: None,
266            });
267            (adj_pred, copula_time)
268        } else {
269            let (verb, verb_time, _, _) = self.consume_verb_with_metadata();
270            let verb_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
271                name: verb,
272                args: self.ctx.terms.alloc_slice([Term::Variable(var)]),
273                world: None,
274            });
275            (verb_pred, verb_time)
276        };
277
278        let combined = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
279            left: noun_pred,
280            op: TokenType::And,
281            right: self.ctx.exprs.alloc(LogicExpr::BinaryOp {
282                left: measure_pred,
283                op: TokenType::And,
284                right: pred_expr,
285            }),
286        });
287
288        let with_time = match verb_time {
289            Time::Past => self.ctx.exprs.alloc(LogicExpr::Temporal {
290                operator: TemporalOperator::Past,
291                body: combined,
292            }),
293            Time::Future => self.ctx.exprs.alloc(LogicExpr::Temporal {
294                operator: TemporalOperator::Future,
295                body: combined,
296            }),
297            _ => combined,
298        };
299
300        Ok(self.ctx.exprs.alloc(LogicExpr::Quantifier {
301            kind: QuantifierKind::Existential,
302            variable: var,
303            body: with_time,
304            island_id: self.current_island,
305        }))
306    }
307
308    fn parse_presupposition(
309        &mut self,
310        subject: &NounPhrase<'a>,
311        presup_kind: PresupKind,
312        negated: bool,
313    ) -> ParseResult<&'a LogicExpr<'a>> {
314        // Delegate to the term-parametric form so the SAME presupposition grammar
315        // ("started skydiving 2 years after …") composes over a relativized
316        // variable too ("the person WHO WON started skydiving …"), not only a
317        // constant subject — LIFT AND SHIFT instead of duplicating the dispatch.
318        self.parse_presupposition_for_term(Term::Constant(subject.noun), presup_kind, negated)
319    }
320
321    fn parse_presupposition_for_term(
322        &mut self,
323        subject_term: Term<'a>,
324        presup_kind: PresupKind,
325        negated: bool,
326    ) -> ParseResult<&'a LogicExpr<'a>> {
327        let unknown = self.interner.intern("?");
328        let complement_verb = if self.check_verb() {
329            Some(self.consume_verb())
330        } else {
331            None
332        };
333        let complement = match complement_verb {
334            Some(verb) => self.ctx.exprs.alloc(LogicExpr::Predicate {
335                name: verb,
336                args: self.ctx.terms.alloc_slice([subject_term]),
337                world: None,
338            }),
339            None => self.ctx.exprs.alloc(LogicExpr::Atom(unknown)),
340        };
341        // The presupposed clause is a real past EVENT — the same shape the
342        // standalone sentence parses to ("Mary lied." →
343        // ∃e(Lie(e) ∧ Agent(e, Mary) ∧ Past(e))) — so the projected content
344        // is derivable by the proof engine, not just printable.
345        let past_event = match complement_verb {
346            Some(verb) => {
347                use crate::ast::logic::NeoEventData;
348                use crate::ast::ThematicRole;
349                self.ctx
350                    .exprs
351                    .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
352                        event_var: self.interner.intern("e"),
353                        verb,
354                        roles: self
355                            .ctx
356                            .roles
357                            .alloc_slice(vec![(ThematicRole::Agent, subject_term)]),
358                        modifiers: self
359                            .ctx
360                            .syms
361                            .alloc_slice(vec![self.interner.intern("Past")]),
362                        suppress_existential: false,
363                        world: None,
364                    })))
365            }
366            None => self.ctx.exprs.alloc(LogicExpr::Temporal {
367                operator: TemporalOperator::Past,
368                body: complement,
369            }),
370        };
371
372        let (mut assertion, presupposition) = match presup_kind {
373            PresupKind::Stop => {
374                let neg = self.ctx.exprs.alloc(LogicExpr::UnaryOp {
375                    op: TokenType::Not,
376                    operand: complement,
377                });
378                (neg, past_event)
379            }
380            PresupKind::Start => {
381                let neg_past = self.ctx.exprs.alloc(LogicExpr::UnaryOp {
382                    op: TokenType::Not,
383                    operand: past_event,
384                });
385                (complement, neg_past)
386            }
387            PresupKind::Regret => {
388                let regret_sym = self.interner.intern("Regret");
389                let regret = self.ctx.exprs.alloc(LogicExpr::Predicate {
390                    name: regret_sym,
391                    args: self.ctx.terms.alloc_slice([subject_term]),
392                    world: None,
393                });
394                (regret, past_event)
395            }
396            PresupKind::Continue | PresupKind::Realize | PresupKind::Know => {
397                let verb_name = match presup_kind {
398                    PresupKind::Continue => self.interner.intern("Continue"),
399                    PresupKind::Realize => self.interner.intern("Realize"),
400                    PresupKind::Know => self.interner.intern("Know"),
401                    _ => unknown,
402                };
403                let main = self.ctx.exprs.alloc(LogicExpr::Predicate {
404                    name: verb_name,
405                    args: self.ctx.terms.alloc_slice([subject_term]),
406                    world: None,
407                });
408                (main, complement)
409            }
410        };
411
412        // Trailing temporal-offset adjunct on the complement event ("started
413        // skydiving 2 YEARS AFTER Leslie", "started skydiving sometime BEFORE
414        // Faye") attaches to the asserted clause; without this it strands.
415        let subj_term = subject_term;
416        if let Some(off) = self.parse_temporal_offset_constraint(subj_term)? {
417            assertion = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
418                left: assertion,
419                op: TokenType::And,
420                right: off,
421            });
422        } else if let Some(off) = self.parse_bare_temporal_constraint(subj_term)? {
423            assertion = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
424                left: assertion,
425                op: TokenType::And,
426                right: off,
427            });
428        }
429
430        // Van der Sandt projection: under negation the assertion is negated but the
431        // PRESUPPOSITION projects (survives outside the ¬). "Mary doesn't regret
432        // lying." → ¬Regret(Mary) [Presup: P(Lie(Mary))] — she still lied.
433        let assertion = if negated {
434            self.ctx.exprs.alloc(LogicExpr::UnaryOp {
435                op: TokenType::Not,
436                operand: assertion,
437            })
438        } else {
439            assertion
440        };
441
442        Ok(self.ctx.exprs.alloc(LogicExpr::Presupposition {
443            assertion,
444            presupposition,
445        }))
446    }
447
448    fn parse_predicate_for_subject(
449        &mut self,
450        subject: &NounPhrase<'a>,
451    ) -> ParseResult<&'a LogicExpr<'a>> {
452        if self.check_verb() {
453            let verb = self.consume_verb();
454
455            // Check for focused object: "eats only rice"
456            if self.check_focus() {
457                let focus_kind = if let TokenType::Focus(k) = self.advance().kind {
458                    k
459                } else {
460                    crate::token::FocusKind::Only
461                };
462
463                let object_np = self.parse_noun_phrase(false)?;
464                let object_term = Term::Constant(object_np.noun);
465
466                let predicate = self.ctx.exprs.alloc(LogicExpr::Predicate {
467                    name: verb,
468                    args: self
469                        .ctx
470                        .terms
471                        .alloc_slice([Term::Constant(subject.noun), object_term.clone()]),
472                    world: None,
473                });
474
475                return Ok(self.ctx.exprs.alloc(LogicExpr::Focus {
476                    kind: focus_kind,
477                    focused: self.ctx.terms.alloc(object_term),
478                    scope: predicate,
479                }));
480            }
481
482            let mut args = vec![Term::Constant(subject.noun)];
483
484            if self.check_content_word() || self.check_article() {
485                let object = self.parse_noun_phrase(false)?;
486                args.push(Term::Constant(object.noun));
487            }
488
489            Ok(self.ctx.exprs.alloc(LogicExpr::Predicate {
490                name: verb,
491                args: self.ctx.terms.alloc_slice(args),
492                world: None,
493            }))
494        } else if matches!(self.peek().kind, TokenType::Is | TokenType::Are) {
495            // Copular predication under focus: "Only dogs are red." →
496            // Only(D, Red(Dogs)), mirroring the verbal "Only dogs bark."
497            self.advance();
498            if self.check_article() {
499                self.advance();
500            }
501            let predicate = match self.advance().kind.clone() {
502                TokenType::Adjective(sym) | TokenType::Noun(sym) | TokenType::ProperName(sym) => {
503                    sym
504                }
505                TokenType::Ambiguous {
506                    primary,
507                    alternatives,
508                } => {
509                    let as_predicate = |t: &TokenType| match t {
510                        TokenType::Adjective(sym)
511                        | TokenType::Noun(sym)
512                        | TokenType::ProperName(sym) => Some(*sym),
513                        _ => None,
514                    };
515                    match as_predicate(&primary)
516                        .or_else(|| alternatives.iter().find_map(as_predicate))
517                    {
518                        Some(sym) => sym,
519                        None => {
520                            return Err(ParseError {
521                                kind: ParseErrorKind::ExpectedContentWord { found: *primary },
522                                span: self.current_span(),
523                            });
524                        }
525                    }
526                }
527                found => {
528                    return Err(ParseError {
529                        kind: ParseErrorKind::ExpectedContentWord { found },
530                        span: self.current_span(),
531                    });
532                }
533            };
534            Ok(self.ctx.exprs.alloc(LogicExpr::Predicate {
535                name: predicate,
536                args: self.ctx.terms.alloc_slice([Term::Constant(subject.noun)]),
537                world: None,
538            }))
539        } else {
540            Ok(self.ctx.exprs.alloc(LogicExpr::Atom(subject.noun)))
541        }
542    }
543
544    fn parse_scopal_adverb(&mut self, subject: &NounPhrase<'a>) -> ParseResult<&'a LogicExpr<'a>> {
545        let operator = if let TokenType::ScopalAdverb(adv) = self.advance().kind.clone() {
546            adv
547        } else {
548            return Err(ParseError {
549                kind: ParseErrorKind::ExpectedScopalAdverb,
550                span: self.current_span(),
551            });
552        };
553
554        if !self.check_verb() {
555            return Err(ParseError {
556                kind: ParseErrorKind::ExpectedVerb {
557                    found: self.peek().kind.clone(),
558                },
559                span: self.current_span(),
560            });
561        }
562
563        // A bare verb keeps the simple predication shape; anything after it
564        // ("almost killed Mary") takes the full VP grammar under the operator.
565        let clause_ends_after_verb = matches!(
566            self.tokens.get(self.current + 1).map(|t| t.kind.clone()),
567            Some(
568                TokenType::Period
569                    | TokenType::Exclamation
570                    | TokenType::EOF
571                    | TokenType::Comma
572                    | TokenType::And
573            ) | None
574        );
575        if !clause_ends_after_verb {
576            use super::verb::LogicVerbParsing;
577            let body = self.parse_predicate_with_subject(subject.noun)?;
578            return Ok(self.ctx.exprs.alloc(LogicExpr::Scopal { operator, body }));
579        }
580
581        let (verb, verb_time, _verb_aspect, _) = self.consume_verb_with_metadata();
582
583        let predicate = self.ctx.exprs.alloc(LogicExpr::Predicate {
584            name: verb,
585            args: self.ctx.terms.alloc_slice([Term::Constant(subject.noun)]),
586            world: None,
587        });
588
589        let with_time = match verb_time {
590            Time::Past => self.ctx.exprs.alloc(LogicExpr::Temporal {
591                operator: TemporalOperator::Past,
592                body: predicate,
593            }),
594            Time::Future => self.ctx.exprs.alloc(LogicExpr::Temporal {
595                operator: TemporalOperator::Future,
596                body: predicate,
597            }),
598            _ => predicate,
599        };
600
601        Ok(self.ctx.exprs.alloc(LogicExpr::Scopal {
602            operator,
603            body: with_time,
604        }))
605    }
606
607    fn parse_superlative(&mut self, subject: &NounPhrase<'a>) -> ParseResult<&'a LogicExpr<'a>> {
608        let adj = if let TokenType::Superlative(adj) = self.advance().kind.clone() {
609            adj
610        } else {
611            return Err(ParseError {
612                kind: ParseErrorKind::ExpectedSuperlativeAdjective,
613                span: self.current_span(),
614            });
615        };
616
617        let domain = self.consume_content_word()?;
618
619        Ok(self.ctx.exprs.alloc(LogicExpr::Superlative {
620            adjective: adj,
621            subject: self.ctx.terms.alloc(Term::Constant(subject.noun)),
622            domain,
623        }))
624    }
625
626    fn parse_comparative(
627        &mut self,
628        subject: &NounPhrase<'a>,
629        _copula_time: Time,
630        difference: Option<&'a Term<'a>>,
631    ) -> ParseResult<&'a LogicExpr<'a>> {
632        // A degree adverb ("somewhat shorter", "slightly wider", "much taller")
633        // may precede the comparative; it stresses the gap but adds no measurable
634        // offset, so skip it — the strict inequality the comparative yields already
635        // captures "more than, by an unspecified amount". Degree adverbs are a
636        // closed lexical class (lexicon `degree_adverbs`).
637        if crate::lexicon::is_degree_adverb(
638            &self.interner.resolve(self.peek().lexeme).to_lowercase(),
639        ) && matches!(
640            self.tokens.get(self.current + 1).map(|t| &t.kind),
641            Some(TokenType::Comparative(_))
642        ) {
643            self.advance(); // degree adverb
644        }
645
646        let comp_tok = self.advance().clone();
647        let comp_surface = self.interner.resolve(comp_tok.lexeme).to_string();
648        let adj = if let TokenType::Comparative(adj) = comp_tok.kind {
649            adj
650        } else {
651            return Err(ParseError {
652                kind: ParseErrorKind::ExpectedComparativeAdjective,
653                span: self.current_span(),
654            });
655        };
656
657        if !self.check(&TokenType::Than) {
658            // A bare comparative predicate with no standard ("X is older", "one is
659            // taller", "the other is faster") — the comparative adjective is a
660            // unary property relative to a contextually-implied standard (the
661            // other entity in a pair). Build Older(X) — the COMPARATIVE surface
662            // ("older"), not the base lemma ("Old"), so the degree isn't lost —
663            // rather than failing; the constraint is preserved (zero meaning
664            // loss), and in an of-pair / list context the complementary
665            // predicates pair up for the prover.
666            let comp_name = {
667                let mut c = comp_surface.chars();
668                match c.next() {
669                    Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
670                    None => comp_surface.clone(),
671                }
672            };
673            return Ok(self.ctx.exprs.alloc(LogicExpr::Predicate {
674                name: self.interner.intern(&comp_name),
675                args: self.ctx.terms.alloc_slice([Term::Constant(subject.noun)]),
676                world: None,
677            }));
678        }
679        self.advance();
680
681        // Check if the comparison target is a number (e.g., "greater than 0")
682        let object_term = if self.check_number() {
683            // Parse number as the comparison target
684            let num_sym = if let TokenType::Number(sym) = self.advance().kind {
685                sym
686            } else {
687                unreachable!()
688            };
689            // The COMPARISON TARGET goes through the one numeral rule, like every other
690            // numeral on this surface. It used to be `parse::<i64>().unwrap_or(0)`, which
691            // turned `taller than 99999999999999999999` into `taller than 0` — the same
692            // silent renumbering as the measure phrase, in the one position where the
693            // renumbered value feeds ORDER reasoning directly.
694            let kind = parse_number_kind(self.interner.resolve(num_sym), num_sym);
695            self.ctx.terms.alloc(Term::Value {
696                kind,
697                unit: None,
698                dimension: None,
699            })
700        } else {
701            // Parse noun phrase as the comparison target — GREEDY so the standard's
702            // PPs / reduced relatives attach ("shorter than the figure WITH THE
703            // YELLOW HAT", "smaller than the tank GOING TO PHILO"). A "than"
704            // standard is nominal — a verb-word head there is a deverbal noun
705            // ("larger than the orange PACK").
706            let saved_ctx = self.nominal_np_context;
707            self.nominal_np_context = true;
708            let object_result = self.parse_noun_phrase(true);
709            self.nominal_np_context = saved_ctx;
710            let object = object_result?;
711
712            // Comparative subdeletion (§2.4): a clausal than-complement with its OWN
713            // gradable dimension — "than the door is WIDE" → compare the matrix
714            // length-degree to the than-clause width-degree:
715            //   ∃d∃d'(Long(desk,d) ∧ Wide(door,d') ∧ d > d').
716            if matches!(
717                self.peek().kind,
718                TokenType::Is | TokenType::Are | TokenType::Was | TokenType::Were
719            ) {
720                let save = self.backtrack_point();
721                self.advance(); // copula
722                if let TokenType::Adjective(adj2) = self.peek().kind {
723                    self.advance();
724                    let d1 = self.next_var_name();
725                    let d2 = self.next_var_name();
726                    let matrix = self.ctx.exprs.alloc(LogicExpr::Predicate {
727                        name: adj,
728                        args: self
729                            .ctx
730                            .terms
731                            .alloc_slice([Term::Constant(subject.noun), Term::Variable(d1)]),
732                        world: None,
733                    });
734                    let than_clause = self.ctx.exprs.alloc(LogicExpr::Predicate {
735                        name: adj2,
736                        args: self
737                            .ctx
738                            .terms
739                            .alloc_slice([Term::Constant(object.noun), Term::Variable(d2)]),
740                        world: None,
741                    });
742                    let gt = self.ctx.exprs.alloc(LogicExpr::Predicate {
743                        name: self.interner.intern(">"),
744                        args: self
745                            .ctx
746                            .terms
747                            .alloc_slice([Term::Variable(d1), Term::Variable(d2)]),
748                        world: None,
749                    });
750                    let conj1 = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
751                        left: matrix,
752                        op: TokenType::And,
753                        right: than_clause,
754                    });
755                    let body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
756                        left: conj1,
757                        op: TokenType::And,
758                        right: gt,
759                    });
760                    let inner = self.ctx.exprs.alloc(LogicExpr::Quantifier {
761                        kind: crate::ast::logic::QuantifierKind::Existential,
762                        variable: d2,
763                        body,
764                        island_id: self.current_island,
765                    });
766                    let outer = self.ctx.exprs.alloc(LogicExpr::Quantifier {
767                        kind: crate::ast::logic::QuantifierKind::Existential,
768                        variable: d1,
769                        body: inner,
770                        island_id: self.current_island,
771                    });
772                    return Ok(outer);
773                }
774                // Clausal ellipsis ("taller than Bill is."): the bare copula
775                // adds nothing — keep it consumed at a clause boundary,
776                // otherwise restore for other readings.
777                if self.at_clause_boundary() {
778                    // copula consumed; comparison proceeds as phrasal
779                } else {
780                    self.backtrack_to(&save);
781                }
782            }
783
784            // SUBJECT side: a descriptive subject (adjectives / possessor / PPs / a
785            // reduced relative) becomes a DISTINCT existential entity carrying its
786            // restrictor — mirroring the standard side — so "the fall Derrick
787            // photographed in 1987 is shorter than …" keeps the reduced relative on
788            // the subject instead of collapsing to the bare head constant. The
789            // variable is used DIRECTLY in the comparison (no later substitution
790            // needed); a bare-head subject stays a constant under the definiteness wrap.
791            let subj_is_desc = !subject.adjectives.is_empty()
792                || subject.possessor.is_some()
793                || !subject.pps.is_empty();
794            let subj_var = if subj_is_desc {
795                Some(self.next_var_name())
796            } else {
797                None
798            };
799            let subj_term = match subj_var {
800                Some(sv) => Term::Variable(sv),
801                None => Term::Constant(subject.noun),
802            };
803
804            // A standard carrying restrictions (adjectives, possessor, PPs, or a
805            // who/that relative clause) becomes a DISTINCT existential entity with a
806            // restrictor so nothing is dropped — same distinct-identity pattern as
807            // the arithmetic comparative / of-pair. A bare name/definite-head stays
808            // a constant.
809            let has_rel = self.check(&TokenType::Who) || self.check(&TokenType::That);
810            let obj_is_desc = has_rel
811                || !object.adjectives.is_empty()
812                || object.possessor.is_some()
813                || !object.pps.is_empty();
814            if obj_is_desc {
815                let obj_var = self.next_var_name();
816                let obj_var_term = Term::Variable(obj_var);
817                let mut restrictor = self.nominal_predication_with_pps(obj_var_term, &object);
818                if has_rel {
819                    self.advance(); // "who" / "that"
820                    let rel = self.parse_relative_clause(obj_var)?;
821                    restrictor = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
822                        left: restrictor,
823                        op: TokenType::And,
824                        right: rel,
825                    });
826                }
827                let cmp = self.ctx.exprs.alloc(LogicExpr::Comparative {
828                    adjective: adj,
829                    subject: self.ctx.terms.alloc(subj_term),
830                    object: self.ctx.terms.alloc(obj_var_term),
831                    difference,
832                    relation: crate::ast::ComparisonRelation::Greater,
833                });
834                let body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
835                    left: restrictor,
836                    op: TokenType::And,
837                    right: cmp,
838                });
839                let quant = self.ctx.exprs.alloc(LogicExpr::Quantifier {
840                    kind: crate::ast::logic::QuantifierKind::Existential,
841                    variable: obj_var,
842                    body,
843                    island_id: self.current_island,
844                });
845                return match subj_var {
846                    Some(sv) => {
847                        let subj_restrictor =
848                            self.nominal_predication_with_pps(Term::Variable(sv), subject);
849                        let body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
850                            left: subj_restrictor,
851                            op: TokenType::And,
852                            right: quant,
853                        });
854                        Ok(self.ctx.exprs.alloc(LogicExpr::Quantifier {
855                            kind: crate::ast::logic::QuantifierKind::Existential,
856                            variable: sv,
857                            body,
858                            island_id: self.current_island,
859                        }))
860                    }
861                    None => self.wrap_with_definiteness(subject.definiteness, subject.noun, quant),
862                };
863            }
864
865            let obj_term = self.ctx.terms.alloc(Term::Constant(object.noun));
866
867            let result = self.ctx.exprs.alloc(LogicExpr::Comparative {
868                adjective: adj,
869                subject: self.ctx.terms.alloc(subj_term),
870                object: obj_term,
871                difference,
872                relation: crate::ast::ComparisonRelation::Greater,
873            });
874
875            let result = match subj_var {
876                Some(sv) => {
877                    let subj_restrictor =
878                        self.nominal_predication_with_pps(Term::Variable(sv), subject);
879                    let body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
880                        left: subj_restrictor,
881                        op: TokenType::And,
882                        right: result,
883                    });
884                    self.ctx.exprs.alloc(LogicExpr::Quantifier {
885                        kind: crate::ast::logic::QuantifierKind::Existential,
886                        variable: sv,
887                        body,
888                        island_id: self.current_island,
889                    })
890                }
891                None => self.wrap_with_definiteness(subject.definiteness, subject.noun, result)?,
892            };
893            return self.wrap_with_definiteness_for_object(
894                object.definiteness,
895                object.noun,
896                result,
897            );
898        };
899
900        // For number comparisons, create a simple Comparative expression
901        Ok(self.ctx.exprs.alloc(LogicExpr::Comparative {
902            adjective: adj,
903            subject: self.ctx.terms.alloc(Term::Constant(subject.noun)),
904            object: object_term,
905            difference,
906            relation: crate::ast::ComparisonRelation::Greater,
907        }))
908    }
909
910    /// Parses the equative frame "X is as ADJ as Y" → an at-least (`≥`) degree
911    /// comparison. The parser is positioned at the first "as"; the subject's
912    /// definiteness wrapping is applied by the caller.
913    fn parse_equative(&mut self, subject: &NounPhrase<'a>) -> ParseResult<&'a LogicExpr<'a>> {
914        self.advance(); // consume the first "as"
915                        // The gradable dimension (an adjective).
916        let adj = match self.advance().kind.clone() {
917            TokenType::Adjective(a) => a,
918            TokenType::Comparative(a) => a,
919            other => {
920                // Use the lexeme as the dimension if it is not a plain adjective token.
921                if let TokenType::Noun(a) = other {
922                    a
923                } else {
924                    self.interner
925                        .intern(&self.interner.resolve(self.previous().lexeme).to_string())
926                }
927            }
928        };
929        // Second "as".
930        if self
931            .interner
932            .resolve(self.peek().lexeme)
933            .eq_ignore_ascii_case("as")
934        {
935            self.advance();
936        }
937        let object = self.parse_noun_phrase(false)?;
938        let obj_term = self.ctx.terms.alloc(Term::Constant(object.noun));
939        let result = self.ctx.exprs.alloc(LogicExpr::Comparative {
940            adjective: adj,
941            subject: self.ctx.terms.alloc(Term::Constant(subject.noun)),
942            object: obj_term,
943            difference: None,
944            relation: crate::ast::ComparisonRelation::GreaterEqual,
945        });
946        let result = self.wrap_with_definiteness(subject.definiteness, subject.noun, result)?;
947        self.wrap_with_definiteness_for_object(object.definiteness, object.noun, result)
948    }
949
950    fn check_number(&self) -> bool {
951        // A clock time ("9:30am", "8:15 pm") is a measure-like value too — it names
952        // a point on the day's timeline that the prover can order, so it is a valid
953        // measure-phrase / PP object ("is at 9:30am", "the meeting at 8:15 pm").
954        matches!(
955            self.peek().kind,
956            TokenType::Number(_) | TokenType::TimeLiteral { .. }
957        )
958    }
959
960    fn parse_measure_phrase(&mut self) -> ParseResult<&'a Term<'a>> {
961        // A clock-time literal is a time-of-day VALUE the prover can order against
962        // other times — represented as minutes-from-midnight (an integer on the
963        // day's timeline) tagged with a `ClockTime` dimension, so "is at 9:30am"
964        // and "the 8:15 pm event" compare numerically. (TODO: timezone-aware times
965        // — carry an offset/zone on the value — when the corpus needs them.)
966        if let TokenType::TimeLiteral {
967            nanos_from_midnight,
968        } = self.peek().kind
969        {
970            self.advance();
971            let minutes = (nanos_from_midnight / 60_000_000_000) as i64;
972            return Ok(self.ctx.terms.alloc(Term::Value {
973                kind: crate::ast::logic::NumberKind::Integer(minutes),
974                unit: None,
975                dimension: Some(crate::ast::logic::Dimension::Time),
976            }));
977        }
978        let num_sym = if let TokenType::Number(sym) = self.advance().kind {
979            sym
980        } else {
981            return Err(ParseError {
982                kind: ParseErrorKind::ExpectedNumber,
983                span: self.current_span(),
984            });
985        };
986
987        let num_str = self.interner.resolve(num_sym);
988        let kind = parse_number_kind(num_str, num_sym);
989
990        // The unit noun after the number ("385 degrees", "5 dollars", "190
991        // points"). An INFLECTED verb (past/future) is never a unit — it is the
992        // matrix predicate ("issued in 1850 sold …" must keep "sold" as the verb,
993        // not read "1850 sold" as a measure), so it is left unconsumed.
994        let next_is_inflected_verb = match &self.peek().kind {
995            TokenType::Verb { time, .. } => matches!(time, Time::Past | Time::Future),
996            TokenType::Ambiguous { primary, .. } => {
997                matches!(**primary, TokenType::Verb { time, .. } if matches!(time, Time::Past | Time::Future))
998            }
999            _ => false,
1000        };
1001        let (unit, dimension) = if matches!(self.peek().kind, TokenType::CalendarUnit(_)) {
1002            // A calendar unit ("years", "months", "days") is a measure unit too:
1003            // "12 years old", "3 weeks late". (The COUNT-UNIT-after/before temporal
1004            // OFFSET is caught earlier in try_temporal_offset, so this only fires
1005            // for the non-offset measure use.)
1006            let unit_word = self.peek().lexeme;
1007            self.advance();
1008            (Some(unit_word), None)
1009        } else if self.check_content_word() && !self.check_article() && !next_is_inflected_verb {
1010            // An ARTICLE after the number is never the unit — it starts a rate
1011            // denominator ("$700 A month") or a following NP; leave it unconsumed.
1012            let unit_word = self.consume_content_word()?;
1013            let unit_str = self.interner.resolve(unit_word).to_lowercase();
1014            let dim = lexicon::lookup_unit_dimension(&unit_str);
1015            (Some(unit_word), dim)
1016        } else {
1017            (None, None)
1018        };
1019
1020        Ok(self.ctx.terms.alloc(Term::Value {
1021            kind,
1022            unit,
1023            dimension,
1024        }))
1025    }
1026
1027    fn counting_np_lookahead(&self) -> Option<u32> {
1028        let n = match self.peek().kind {
1029            TokenType::Number(sym) => self.interner.resolve(sym).parse::<u32>().ok()?,
1030            _ => return None,
1031        };
1032        // Scan ≥1 modifier (adjective or a ProperName premodifier), then require a
1033        // common-noun head. The modifier is what proves this is a count — "6 BROWN
1034        // manatees", "640 TWITTER followers", "78 LINKEDIN connections" — not a
1035        // measure ("190 points" has no modifier and stays on the measure path).
1036        let mut i = self.current + 1;
1037        let mut saw_modifier = false;
1038        while matches!(
1039            self.tokens.get(i).map(|t| &t.kind),
1040            Some(TokenType::Adjective(_))
1041                | Some(TokenType::NonIntersectiveAdjective(_))
1042                | Some(TokenType::ProperName(_))
1043        ) {
1044            saw_modifier = true;
1045            i += 1;
1046        }
1047        if !saw_modifier {
1048            return None;
1049        }
1050        let head_is_noun = match self.tokens.get(i).map(|t| &t.kind) {
1051            Some(TokenType::Noun(_)) | Some(TokenType::Item) | Some(TokenType::Items) => true,
1052            // A verb-word head ("49 previous JUMPS", "six previous RUNS") is a
1053            // DEVERBAL NOUN here — a number followed by an adjective cannot
1054            // precede a finite verb, so the head is nominal. The object-NP path
1055            // recovers it as the head (via nominal_np_context).
1056            Some(TokenType::Verb { .. }) => true,
1057            Some(TokenType::Ambiguous {
1058                primary,
1059                alternatives,
1060            }) => {
1061                matches!(**primary, TokenType::Noun(_) | TokenType::Verb { .. })
1062                    || alternatives
1063                        .iter()
1064                        .any(|t| matches!(t, TokenType::Noun(_) | TokenType::Verb { .. }))
1065            }
1066            _ => false,
1067        };
1068        head_is_noun.then_some(n)
1069    }
1070}
1071
1072/// The measure phrase's numeral, as the value it denotes — or, when it denotes no value we
1073/// can hold, as the SYMBOL it was written with.
1074///
1075/// `unwrap_or` was the bug. `s.parse::<i64>().unwrap_or(0)` turned `99999999999999999999
1076/// dollars` into **zero** dollars, and `s.parse::<f64>().unwrap_or(0.0)` turned a malformed
1077/// decimal into `0.0`, and the renumbered value travelled through
1078/// `proof_convert::term_to_proof_term` to `ProofTerm::Constant` as if it were what the author
1079/// wrote. Zero is the worst possible default here: it is a legal measure, it compares, and it
1080/// makes a premise about a huge price agree with a goal about no price at all.
1081///
1082/// A number this surface cannot VALUE stays SYMBOLIC and keeps its lexeme, which is what
1083/// `verb.rs`'s measure-offset reader already does. The lexeme is the identity.
1084pub(super) fn parse_number_kind(s: &str, sym: crate::intern::Symbol) -> NumberKind {
1085    if let Ok(n) = s.parse::<i64>() {
1086        return NumberKind::Integer(n);
1087    }
1088    if s.contains('.') {
1089        if let Ok(f) = s.parse::<f64>() {
1090            return NumberKind::Real(f);
1091        }
1092    }
1093    NumberKind::Symbolic(sym)
1094}