logicaffeine_language/parser/noun.rs
1//! Noun phrase parsing with determiners, adjectives, and possessives.
2//!
3//! This module handles the full complexity of English noun phrases including:
4//!
5//! - **Determiners**: Articles (a, the), quantifiers (every, some, no)
6//! - **Adjectives**: Pre-nominal modifiers, intersective vs subsective
7//! - **Possessives**: "John's", "his", genitive constructions
8//! - **Proper names**: Capitalized constants
9//! - **Numeric literals**: Numbers as noun phrases for comparisons
10//! - **Prepositional phrases**: Post-nominal "of" constructions
11//! - **Superlatives**: "the tallest", "the most interesting"
12//!
13//! The parsed [`NounPhrase`] struct carries definiteness, adjectives, the head
14//! noun, optional possessor, and attached prepositional phrases.
15
16use super::clause::ClauseParsing;
17use super::pragmatics::PragmaticsParsing;
18use super::{ParseResult, Parser};
19use crate::ast::{LogicExpr, NounPhrase, Term};
20use crate::drs::{Case, Gender, Number};
21use crate::lexicon::Definiteness;
22use crate::token::TokenType;
23use logicaffeine_base::SymbolEq;
24
25/// The preposition a declared CATEGORY contributes to a definite-description
26/// label, so the label un-fuses to the SAME relation the prepositional-phrase
27/// form produces. TEMPORAL ("the 2003 holiday" ↔ "in 2003") and LOCATIVE ("the
28/// Florida trip" ↔ "in Florida") both → `In`; PERSONAL ("the Bill trip" ↔ "with
29/// Bill") → `With`.
30///
31/// The lexicon SORT is consulted first where it is decisive (`Place`/`Time` →
32/// `In`, `Human` → `With`), but several calendar/region nouns carry an
33/// `Abstract` sort in the lexicon (year, month, week, decade, century, state),
34/// so an explicit lemma set backs the sort up. A category that maps to neither
35/// dimension (e.g. "vegetable") returns `None` and the label stays fused.
36fn category_preposition(category_lemma_lower: &str) -> Option<&'static str> {
37 const TEMPORAL: &[&str] = &["year", "month", "day", "date", "week", "decade", "century"];
38 const LOCATIVE: &[&str] = &[
39 "state", "city", "country", "province", "region", "town", "place",
40 ];
41 const PERSONAL: &[&str] = &["friend", "person", "man", "woman", "colleague", "companion"];
42
43 if TEMPORAL.contains(&category_lemma_lower) || LOCATIVE.contains(&category_lemma_lower) {
44 return Some("In");
45 }
46 if PERSONAL.contains(&category_lemma_lower) {
47 return Some("With");
48 }
49 match crate::lexicon::lookup_sort(category_lemma_lower) {
50 Some(crate::lexicon::Sort::Place) | Some(crate::lexicon::Sort::Time) => Some("In"),
51 Some(crate::lexicon::Sort::Human) => Some("With"),
52 _ => None,
53 }
54}
55
56/// Trait for parsing noun phrases.
57///
58/// Provides methods for parsing determiners, adjectives, possessives,
59/// and converting noun phrases to first-order terms.
60pub trait NounParsing<'a, 'ctx, 'int> {
61 /// Parses a full noun phrase with optional greedy PP attachment.
62 fn parse_noun_phrase(&mut self, greedy: bool) -> ParseResult<NounPhrase<'a>>;
63 /// Parses a noun phrase suitable for relative clause antecedent.
64 fn parse_noun_phrase_for_relative(&mut self) -> ParseResult<NounPhrase<'a>>;
65 /// Converts a parsed noun phrase to a first-order term.
66 fn noun_phrase_to_term(&self, np: &NounPhrase<'a>) -> Term<'a>;
67 /// Checks for possessive marker ('s).
68 fn check_possessive(&self) -> bool;
69 /// Checks for "of" preposition (possessive or partitive).
70 fn check_of_preposition(&self) -> bool;
71 /// Checks for proper name or label (capitalized).
72 fn check_proper_name_or_label(&self) -> bool;
73 /// Whether a token of this kind is a proper name or a label — a word the noun-phrase
74 /// parser compounds into a multi-word name.
75 fn is_proper_name_or_label(&self, kind: &TokenType) -> bool;
76 /// Whether the cursor opens an object-gap reduced relative (subject + transitive
77 /// verb + empty object slot), e.g. "Tara won" in "the prize Tara won".
78 fn peek_reduced_object_relative(&self) -> bool;
79 /// Whether the cursor sits on a DEFINITE article that opens a noun phrase whose
80 /// head is modified by a reduced object relative ("the friend Simon went with",
81 /// "the waterfall Derrick photographed"). Used by the object-NP dispatcher to
82 /// route such an object through the full `parse_noun_phrase` machinery instead
83 /// of pre-consuming the article (which would hide the relative).
84 fn peek_definite_reduced_relative_object(&self) -> bool;
85 /// Checks for possessive pronoun (his, her, its, their).
86 fn check_possessive_pronoun(&self) -> bool;
87 /// Resolves a numeric LABEL ("the 2003 holiday", "the 1850 stamp"): returns
88 /// the head symbol, FUSED (`2003_holiday`) by default, but UN-FUSED to the
89 /// bare head plus a category relation restrictor (pushed onto
90 /// `measure_restrictors`) when `n` names a DRS-declared item whose category
91 /// maps to a preposition.
92 fn numeric_label_head(
93 &mut self,
94 n: i64,
95 head: crate::intern::Symbol,
96 definiteness: Option<Definiteness>,
97 measure_restrictors: &mut Vec<&'a LogicExpr<'a>>,
98 ) -> crate::intern::Symbol;
99 /// Consume a numeric-label HEAD preferring the NOUN reading of a verb-ambiguous
100 /// word, so the fused symbol matches the noun-compound form ("the 2001 trip" →
101 /// `2001_trip`, not the verb lemma `2001_Trip`). A verb-only head ("stamp")
102 /// has no noun reading and keeps its lemma; a plain noun ("holiday") is already
103 /// the noun. (The un-fused predicate is capitalized downstream regardless.)
104 fn consume_label_head_noun_first(&mut self) -> ParseResult<crate::intern::Symbol>;
105}
106
107impl<'a, 'ctx, 'int> NounParsing<'a, 'ctx, 'int> for Parser<'a, 'ctx, 'int> {
108 fn parse_noun_phrase(&mut self, greedy: bool) -> ParseResult<NounPhrase<'a>> {
109 let mut definiteness = None;
110 let mut adjectives = Vec::new();
111 let mut non_intersective_prefix: Option<crate::intern::Symbol> = None;
112 let mut possessor_from_pronoun: Option<&'a NounPhrase<'a>> = None;
113 let mut superlative_adj: Option<crate::intern::Symbol> = None;
114 // Attributive measure-adjective restrictors ("the 80 year old doll" →
115 // Old(_PP_SELF_, 80 years)); merged into the NP's pps after the head, so a
116 // degree property survives in every position the pps flow through.
117 let mut measure_restrictors: Vec<&'a LogicExpr<'a>> = Vec::new();
118
119 // Phase 35: Support numeric literals as noun phrases (e.g., "equal to 42").
120 // BUT only when the number stands alone — a number FOLLOWED by a content
121 // word heads a larger NP ("28 inch wingspan", "640 Twitter followers"),
122 // which the numeric-head compound logic below folds; early-returning here
123 // would strand the rest ("inch wingspan").
124 if let TokenType::Number(sym) = self.peek().kind {
125 let number_modifies_head = matches!(
126 self.tokens.get(self.current + 1).map(|t| &t.kind),
127 Some(TokenType::Noun(_))
128 | Some(TokenType::ProperName(_))
129 | Some(TokenType::Adjective(_))
130 | Some(TokenType::Verb { .. })
131 | Some(TokenType::Ambiguous { .. })
132 );
133 if !number_modifies_head {
134 self.advance();
135 return Ok(NounPhrase {
136 definiteness: None,
137 adjectives: &[],
138 noun: sym,
139 possessor: None,
140 pps: &[],
141 superlative: None,
142 });
143 }
144 }
145
146 if self.check_possessive_pronoun() {
147 let token = self.advance().clone();
148 let (gender, number) = match &token.kind {
149 TokenType::Pronoun {
150 gender,
151 number,
152 case: Case::Possessive,
153 } => (*gender, *number),
154 TokenType::Ambiguous {
155 primary,
156 alternatives,
157 } => {
158 let mut found = None;
159 if let TokenType::Pronoun {
160 gender,
161 number,
162 case: Case::Possessive,
163 } = **primary
164 {
165 found = Some((gender, number));
166 }
167 if found.is_none() {
168 for alt in alternatives {
169 if let TokenType::Pronoun {
170 gender,
171 number,
172 case: Case::Possessive,
173 } = alt
174 {
175 found = Some((*gender, *number));
176 break;
177 }
178 }
179 }
180 found.unwrap_or((Gender::Unknown, Number::Singular))
181 }
182 _ => (Gender::Unknown, Number::Singular),
183 };
184
185 let resolved = self.resolve_pronoun(gender, number)?;
186 let resolved_sym = match resolved {
187 super::ResolvedPronoun::Variable(s) | super::ResolvedPronoun::Constant(s) => s,
188 };
189
190 let possessor_np = NounPhrase {
191 definiteness: None,
192 adjectives: &[],
193 noun: resolved_sym,
194 possessor: None,
195 pps: &[],
196 superlative: None,
197 };
198 possessor_from_pronoun = Some(self.ctx.nps.alloc(possessor_np));
199 definiteness = Some(Definiteness::Definite);
200 } else if let TokenType::Article(def) = self.peek().kind {
201 // Phase 35: Disambiguate "a" as variable vs article
202 // If "a" or "an" is followed by a verb/copula/modal, it's a variable name, not an article
203 let is_variable_a = {
204 let lexeme = self.interner.resolve(self.peek().lexeme).to_lowercase();
205 if lexeme == "a" || lexeme == "an" {
206 if let Some(next) = self.tokens.get(self.current + 1) {
207 // A PROGRESSIVE verb (an "-ing" gerund) directly before a
208 // noun head is a PRE-NOMINAL MODIFIER, not a predicate — so
209 // "a kayaking REGIMEN", "a running SHOE" are indefinite NPs
210 // and "a" is an article, not a logic variable. Only this
211 // gerund+noun shape is excluded; "a runs"/"a sees Bob"/"a =
212 // b" keep the variable reading.
213 let gerund_premodifier = matches!(
214 next.kind,
215 TokenType::Verb {
216 aspect: crate::lexicon::Aspect::Progressive,
217 ..
218 }
219 ) && matches!(
220 self.tokens.get(self.current + 2).map(|t| &t.kind),
221 Some(TokenType::Noun(_)) | Some(TokenType::Ambiguous { .. })
222 );
223 !gerund_premodifier
224 && matches!(
225 next.kind,
226 TokenType::Is | TokenType::Are | TokenType::Was | TokenType::Were | // Copula
227 TokenType::Verb { .. } | // Main verb
228 TokenType::Auxiliary(_) | // will, did
229 TokenType::Must | TokenType::Can | TokenType::Should | TokenType::May | // Modals
230 TokenType::Could | TokenType::Would | TokenType::Shall | TokenType::Might |
231 TokenType::Identity | TokenType::Equals // "a = b"
232 )
233 } else {
234 false
235 }
236 } else {
237 false
238 }
239 };
240
241 if !is_variable_a {
242 definiteness = Some(def);
243 self.advance();
244 }
245 }
246
247 if self.check_superlative() {
248 if let TokenType::Superlative(adj) = self.advance().kind {
249 superlative_adj = Some(adj);
250 }
251 }
252
253 if self.check_non_intersective_adjective() {
254 if let TokenType::NonIntersectiveAdjective(adj) = self.advance().kind {
255 non_intersective_prefix = Some(adj);
256 }
257 }
258
259 loop {
260 if self.is_at_end() {
261 break;
262 }
263
264 // A gerund (-ing form) directly before a noun head in a DEFINITE
265 // description is an attributive MODIFIER, not part of the head: "the
266 // hunting trip" → Trip(x) ∧ Hunt(x). Keeping the attribute as a
267 // first-class predicate (un-fused) means "hunting" is the same key
268 // wherever the entity is named ("the hunting vacation", "the hunting
269 // trip"), so the discourse layer can resolve them to one referent.
270 // Restricted to definites because reference-resolution applies to
271 // definite descriptions; a bare-plural object ("used bowling pins")
272 // becomes a constant with no restrictor to hold a separate predicate,
273 // so its modifier must stay folded into the head symbol (Bowl_pins).
274 if let TokenType::Verb {
275 lemma,
276 aspect: crate::lexicon::Aspect::Progressive,
277 ..
278 } = self.peek().kind
279 {
280 let next_is_head = matches!(
281 self.tokens.get(self.current + 1).map(|t| &t.kind),
282 Some(TokenType::Noun(_))
283 | Some(TokenType::ProperName(_))
284 | Some(TokenType::Ambiguous { .. })
285 );
286 if next_is_head && definiteness == Some(Definiteness::Definite) {
287 self.advance();
288 adjectives.push(lemma);
289 continue;
290 }
291 }
292
293 // A proper name directly before a common-noun head in a DEFINITE
294 // description is an attributive LABEL modifier, not part of the head:
295 // "the Florida trip" → Trip(x) ∧ Florida(x); "the Woodard family" →
296 // Family(x) ∧ Woodard(x). Un-fusing keeps the label a first-class key
297 // so the discourse layer resolves "the Florida trip" and "the Florida
298 // vacation" (or "the Woodard family" and "the Woodard estate") to one
299 // referent. Definite-gated, so a bare named entity ("Lake Tahoe",
300 // "Leiman Manor") stays a single constant and never un-fuses.
301 if let TokenType::ProperName(label) = self.peek().kind {
302 let next_is_common_head = matches!(
303 self.tokens.get(self.current + 1).map(|t| &t.kind),
304 Some(TokenType::Noun(_)) | Some(TokenType::Ambiguous { .. })
305 );
306 if next_is_common_head && definiteness == Some(Definiteness::Definite) {
307 self.advance();
308 // A proper name that names a DECLARED item ("Florida"
309 // registered as a state, "Bill" as a friend) un-fuses to a
310 // P(_PP_SELF_, <name>) restrictor instead of a bare predicate,
311 // converging with the prepositional-phrase form ("the trip was
312 // in Florida" → In(x, Florida); "…with Bill" → With(x, Bill)).
313 // The object term mirrors the PP form's constant EXACTLY so the
314 // two unify. An undeclared label ("the Woodard family") keeps
315 // its bare-predicate behavior.
316 let unfused = self.drs.item_category(label).and_then(|category| {
317 let cat_lemma = Self::singularize_noun(self.interner.resolve(category));
318 category_preposition(&cat_lemma.to_lowercase())
319 });
320 if let Some(prep) = unfused {
321 let prep_sym = self.interner.intern(prep);
322 let placeholder = self.interner.intern("_PP_SELF_");
323 let pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
324 name: prep_sym,
325 args: self
326 .ctx
327 .terms
328 .alloc_slice([Term::Variable(placeholder), Term::Constant(label)]),
329 world: None,
330 });
331 measure_restrictors.push(pred);
332 } else {
333 adjectives.push(label);
334 }
335 continue;
336 }
337 }
338
339 // Compound color / quality term: a NOUN immediately before an
340 // ADJECTIVE that is in turn followed by a HEAD NOUN ("LIME green
341 // SHIRT", "MIDNIGHT blue CAR", "BLOOD red CAR") — the noun pre-modifies
342 // the adjective; fold the pair into one "Lime_green" adjective. The
343 // following head-noun requirement distinguishes this from a head noun
344 // + a post-nominal secondary predicate ("painted the DOOR red.", where
345 // "door" is the head and "red" a resultative): there no noun follows.
346 let color_compound = matches!(self.peek().kind, TokenType::Noun(_))
347 && matches!(
348 self.tokens.get(self.current + 1).map(|t| &t.kind),
349 Some(TokenType::Adjective(_))
350 )
351 && matches!(
352 self.tokens.get(self.current + 2).map(|t| &t.kind),
353 Some(TokenType::Noun(_))
354 | Some(TokenType::ProperName(_))
355 | Some(TokenType::Adjective(_))
356 | Some(TokenType::Verb { .. })
357 | Some(TokenType::Ambiguous { .. })
358 );
359 if color_compound {
360 let n = if let TokenType::Noun(n) = self.peek().kind {
361 n
362 } else {
363 unreachable!()
364 };
365 self.advance(); // the noun modifier
366 let a = if let TokenType::Adjective(a) = self.peek().kind {
367 a
368 } else {
369 unreachable!()
370 };
371 self.advance(); // the adjective
372 let compound = self.interner.intern(&format!(
373 "{}_{}",
374 self.interner.resolve(n),
375 self.interner.resolve(a)
376 ));
377 adjectives.push(compound);
378 continue;
379 }
380
381 // Attributive measure-adjective: "80 year old [doll]", "28 inch long
382 // [wing]" — a measure phrase (Number + unit) modifying a following
383 // gradable ADJECTIVE is a degree property of the head, mirroring the
384 // predicative "is 80 years old" → Old(x, 80 years). Emit
385 // Adj(_PP_SELF_, value) so the degree AND its unit survive rather than
386 // stranding the unit token. Gated on the third token being an ADJECTIVE,
387 // so "28 inch wingspan" (a measure-noun compound) is left to the head.
388 let measure_num = match self.peek().kind {
389 TokenType::Cardinal(n) => Some(crate::ast::logic::NumberKind::Integer(n as i64)),
390 TokenType::Number(s) => {
391 let raw = self.interner.resolve(s).replace(',', "");
392 Some(
393 raw.parse::<i64>()
394 .map(crate::ast::logic::NumberKind::Integer)
395 .unwrap_or(crate::ast::logic::NumberKind::Symbolic(s)),
396 )
397 }
398 _ => None,
399 };
400 if let Some(kind) = measure_num {
401 let unit_tok = self.tokens.get(self.current + 1);
402 let unit_is_measure = unit_tok.map_or(false, |t| {
403 matches!(t.kind, TokenType::CalendarUnit(_))
404 || matches!(t.kind, TokenType::Noun(_)
405 if crate::lexicon::lookup_unit_dimension(
406 &self.interner.resolve(t.lexeme).to_lowercase()).is_some())
407 });
408 let adj_after = self.tokens.get(self.current + 2).and_then(|t| {
409 if let TokenType::Adjective(a) = t.kind {
410 Some(a)
411 } else {
412 None
413 }
414 });
415 if unit_is_measure {
416 if let Some(adj) = adj_after {
417 let unit_sym = unit_tok.unwrap().lexeme;
418 self.advance(); // number
419 self.advance(); // unit
420 self.advance(); // gradable adjective
421 let placeholder = self.interner.intern("_PP_SELF_");
422 let value = Term::Value {
423 kind,
424 unit: Some(unit_sym),
425 dimension: None,
426 };
427 let pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
428 name: adj,
429 args: self
430 .ctx
431 .terms
432 .alloc_slice([Term::Variable(placeholder), value]),
433 world: None,
434 });
435 measure_restrictors.push(pred);
436 continue;
437 }
438 }
439 }
440
441 let is_adjective = matches!(self.peek().kind, TokenType::Adjective(_));
442 if !is_adjective {
443 break;
444 }
445
446 // A verb-only or ambiguous word after an adjective is the head noun
447 // ("the rare stamp", "the long run") — but ONLY inside a
448 // determiner-headed NP. Without the article gate, "studies hard
449 // pass …" would wrongly read the main verb "pass" as a noun ("hard"
450 // there is an adverb). The lexicon's is_adverb misses "hard", so the
451 // article is the reliable signal.
452 let next_is_content = if self.current + 1 < self.tokens.len() {
453 let next = &self.tokens[self.current + 1].kind;
454 matches!(
455 next,
456 TokenType::Noun(_) | TokenType::Adjective(_) | TokenType::ProperName(_)
457 ) || ((definiteness.is_some() || self.nominal_np_context)
458 && matches!(next, TokenType::Verb { .. } | TokenType::Ambiguous { .. }))
459 } else {
460 false
461 };
462
463 if next_is_content {
464 if let TokenType::Adjective(adj) = self.advance().kind {
465 adjectives.push(adj);
466 }
467 } else {
468 break;
469 }
470 }
471
472 // "the 8:15 pm event" / "the 9:30am outing" — a clock time names the head
473 // noun; compound the minutes-from-midnight into the symbol so the entity is
474 // identified by its time ("1215_event"), distinct from "570_outing".
475 let base_noun = if let TokenType::TimeLiteral {
476 nanos_from_midnight,
477 } = self.peek().kind
478 {
479 let minutes = nanos_from_midnight / 60_000_000_000;
480 let next_is_head = matches!(
481 self.tokens.get(self.current + 1).map(|t| &t.kind),
482 Some(TokenType::Noun(_))
483 | Some(TokenType::ProperName(_))
484 | Some(TokenType::Adjective(_))
485 | Some(TokenType::Verb { .. })
486 | Some(TokenType::Ambiguous { .. })
487 );
488 if next_is_head {
489 self.advance(); // consume the time literal
490 let head = self.consume_content_word()?;
491 let head_str = self.interner.resolve(head).to_string();
492 self.interner.intern(&format!("{}_{}", minutes, head_str))
493 } else {
494 self.consume_content_word()?
495 }
496 }
497 // "the 1848 home" / "the 1834 flood" — cardinal used as a year/label modifier
498 // before the head noun; compound the two into a single symbol.
499 else if let TokenType::Cardinal(n) = self.peek().kind {
500 // The head after a count/label cardinal can tokenize as a noun, a
501 // proper name, an adjective, or — for words that are also verbs
502 // ("dances", "places") — a verb / ambiguous token.
503 let next_is_content = self.tokens.get(self.current + 1).map_or(false, |t| {
504 matches!(
505 t.kind,
506 TokenType::Noun(_)
507 | TokenType::ProperName(_)
508 | TokenType::Adjective(_)
509 | TokenType::Verb { .. }
510 | TokenType::Ambiguous { .. }
511 // "item"/"items" are nouns in declarative NL ("the $275
512 // item"); the lexer keeps them as keyword tokens.
513 | TokenType::Item
514 | TokenType::Items
515 )
516 });
517 if next_is_content {
518 self.advance(); // consume the cardinal
519 let head = self.consume_label_head_noun_first()?;
520 self.numeric_label_head(n as i64, head, definiteness, &mut measure_restrictors)
521 } else if n == 1 {
522 // "the one who paid $150" / "the one with 804 followers" / "the one
523 // from St. Paul" — "one" used PRONOMINALLY (no following head noun)
524 // is the impersonal pronoun, a generic entity, not the numeral 1.
525 self.advance(); // consume "one"
526 self.interner.intern("One")
527 } else {
528 self.consume_content_word()?
529 }
530 }
531 // "the 2003 holiday" / "the 1850 stamp" — a YEAR/numeric label lexes as a
532 // bare Number (digits), not a word-Cardinal, but plays the same role: it
533 // names the head noun. Route it through the SAME label logic so a declared
534 // item un-fuses to its category relation and an undeclared one stays fused.
535 else if let TokenType::Number(num_sym) = self.peek().kind {
536 let next_is_content = self.tokens.get(self.current + 1).map_or(false, |t| {
537 matches!(
538 t.kind,
539 TokenType::Noun(_)
540 | TokenType::ProperName(_)
541 | TokenType::Adjective(_)
542 | TokenType::Verb { .. }
543 | TokenType::Ambiguous { .. }
544 | TokenType::Item
545 | TokenType::Items
546 )
547 });
548 // Only an INTEGER label (a year / instance number) compounds with the
549 // head; a unit measure ("3.5 inch") is left to the measure path, and a
550 // non-integer Number never names an instance.
551 let int_value = self
552 .interner
553 .resolve(num_sym)
554 .replace(',', "")
555 .parse::<i64>()
556 .ok();
557 match (next_is_content, int_value) {
558 (true, Some(n)) => {
559 self.advance(); // consume the number
560 let head = self.consume_label_head_noun_first()?;
561 self.numeric_label_head(n, head, definiteness, &mut measure_restrictors)
562 }
563 _ => self.consume_content_word()?,
564 }
565 } else {
566 self.consume_content_word()?
567 };
568
569 let noun = if let Some(prefix) = non_intersective_prefix {
570 let prefix_str = self.interner.resolve(prefix);
571 let base_str = self.interner.resolve(base_noun);
572 let compound = format!("{}-{}", prefix_str, base_str);
573 self.interner.intern(&compound)
574 } else {
575 base_noun
576 };
577
578 // Absorb EVERY consecutive proper-name label into the head ("Delta Gamma Pi" →
579 // Delta_Gamma_Pi, "Beta Pi Omega" → Beta_Pi_Omega) — a multi-word name can be
580 // 3+ words, not just two.
581 // …but in a DETERMINER-headed NP ("the prize Tara won", "the waterfall
582 // Derrick photographed") a proper name that opens an object-gap reduced
583 // relative is the relative's SUBJECT, NOT a label compounded into the head —
584 // leave it for the reduced-relative detection below. A bare multi-word proper
585 // name ("Ray Ricardo won") has no determiner, and an apposition with an overt
586 // object ("the dancer Tara won the prize") has no gap, so both still compound.
587 let mut noun = noun;
588 while self.check_proper_name_or_label()
589 && !(definiteness.is_some() && self.peek_reduced_object_relative())
590 {
591 let label = self.consume_content_word()?;
592 noun = self.interner.intern(&format!(
593 "{}_{}",
594 self.interner.resolve(noun),
595 self.interner.resolve(label)
596 ));
597 }
598 let noun = noun;
599
600 // US "City, ST" address — a place proper name followed by ", " + a
601 // two-letter ALL-CAPS state abbreviation is ONE location entity
602 // ("Charlestown, CT" → Charlestown_CT, "Barnstable, ME" → Barnstable_ME).
603 // The all-caps gate excludes Title-case names ("Al", "Bo") and ordinary
604 // list/clause commas (names are never two-letter all-caps), so this never
605 // swallows a coordinator.
606 let noun = if self.check(&TokenType::Comma) {
607 let state_abbr = matches!(
608 self.tokens.get(self.current + 1).map(|t| &t.kind),
609 Some(TokenType::ProperName(s))
610 if { let l = self.interner.resolve(*s); l.len() == 2 && l.chars().all(|c| c.is_ascii_uppercase()) }
611 );
612 let head_is_proper = self
613 .interner
614 .resolve(noun)
615 .chars()
616 .next()
617 .map_or(false, |c| c.is_ascii_uppercase());
618 if state_abbr && head_is_proper {
619 self.advance(); // consume the comma
620 let st = self.consume_content_word()?;
621 let compound = format!(
622 "{}_{}",
623 self.interner.resolve(noun),
624 self.interner.resolve(st)
625 );
626 self.interner.intern(&compound)
627 } else {
628 noun
629 }
630 } else {
631 noun
632 };
633
634 // Noun-noun compounds ("stop bit", "data bits", "grant signal"): a
635 // PLAIN noun directly after the head joins it as one compound head.
636 // An Ambiguous noun/verb word ("signal") joins ONLY when a copula
637 // follows it — there the verb reading is impossible — so genuine
638 // ambiguity ("Time flies like an arrow") keeps its verb reading and
639 // the forest enumerates the rest.
640 let mut noun = noun;
641 loop {
642 // The function word "as" lexes as a Noun (unknown-word fallback) but
643 // is never a compound-noun part — it introduces a predicative
644 // complement ("has Al Acosta AS its mayor"). Stop the compound here so
645 // the "as"-phrase is left for the verb path, not bundled into the head.
646 if matches!(self.peek().kind, TokenType::Noun(_))
647 && self
648 .interner
649 .resolve(self.peek().lexeme)
650 .eq_ignore_ascii_case("as")
651 {
652 break;
653 }
654 let next = match &self.peek().kind {
655 TokenType::Noun(next) => *next,
656 TokenType::Ambiguous {
657 primary,
658 alternatives,
659 } => {
660 let noun_reading = if let TokenType::Noun(n) = &**primary {
661 Some(*n)
662 } else {
663 alternatives.iter().find_map(|t| {
664 if let TokenType::Noun(n) = t {
665 Some(*n)
666 } else {
667 None
668 }
669 })
670 };
671 let copula_after = matches!(
672 self.tokens.get(self.current + 1).map(|t| &t.kind),
673 Some(TokenType::Is)
674 | Some(TokenType::Are)
675 | Some(TokenType::Was)
676 | Some(TokenType::Were)
677 );
678 // Inside an OBJECT/complement NP (greedy == false the clause
679 // already has its main verb) an ambiguous noun/verb word that
680 // is NOT itself followed by its own argument cannot be a verb —
681 // it joins the head as a compound ("has a glass head.", "holds
682 // a paper clip.", "played second base WON"). The following
683 // token confirms this: a clause boundary (Period/EOF/comma/
684 // and/or) or a FINITE verb/copula (the matrix or next clause's
685 // verb — "second base" then matrix "won"/"is") both rule out a
686 // verb reading of the ambiguous word. A clause subject (greedy
687 // == true) keeps the verb reading so "The man runs." is not
688 // eaten; wh-extraction is excluded (the gap leaves the embedded
689 // verb at a boundary, "…Mary said Bill saw?").
690 let object_compound_boundary = !greedy
691 && self.filler_gap.is_none()
692 && matches!(
693 self.tokens.get(self.current + 1).map(|t| &t.kind),
694 None | Some(TokenType::Period)
695 | Some(TokenType::EOF)
696 | Some(TokenType::Comma)
697 | Some(TokenType::And)
698 | Some(TokenType::Or)
699 | Some(TokenType::Verb { .. })
700 | Some(TokenType::Is)
701 | Some(TokenType::Are)
702 | Some(TokenType::Was)
703 | Some(TokenType::Were)
704 );
705 // A nominal context (copula complement / PP object /
706 // comparative standard) likewise rules out the verb reading:
707 // "is the Russell Road PROJECT", "the $5.25 PURCHASE".
708 // After a numeric-MEASURE head ("60_gallon …"), the following
709 // words are the measured head COMPOUND ("60 gallon FISH TANK"), so
710 // an ambiguous noun/verb word ("fish") joins the head even in a
711 // greedy subject — a measure premodifier cannot be followed by a
712 // finite verb, so the ambiguity resolves to noun.
713 let head_is_numeric_measure = self
714 .interner
715 .resolve(noun)
716 .chars()
717 .next()
718 .map_or(false, |c| c.is_ascii_digit());
719 match (
720 noun_reading,
721 copula_after
722 || object_compound_boundary
723 || self.nominal_np_context
724 || head_is_numeric_measure,
725 ) {
726 (Some(n), true) => n,
727 _ => break,
728 }
729 }
730 // A verb-only word ("stamp", "print") after a numeric/label head
731 // is a compound-noun part ("the 125000 stamp"). A bare number
732 // cannot head an NP that acts, so a numeric head takes the
733 // following verb-word as its real head noun whatever follows —
734 // BUT only in BASE form (surface == lemma): "stamp"/"print" read
735 // as nouns, while an inflected form ("in 1850 sold …", "runs") is
736 // a genuine verb and must not be eaten. Otherwise we require a
737 // copula after so "the man runs fast" keeps "runs" as the verb.
738 TokenType::Verb { lemma, .. } => {
739 let head_is_numeric = {
740 // Accept decimal/grouped money amounts as numeric heads
741 // ("$5.25 purchase" → 5.25, "$1,800 stamp" → 1,800) so the
742 // deverbal-noun fold fires — a bare number can't head an
743 // acting NP, so the following verb-word is its real head.
744 let h = self.interner.resolve(noun);
745 !h.is_empty()
746 && h.chars().any(|c| c.is_ascii_digit())
747 && h.chars()
748 .all(|c| c.is_ascii_digit() || c == '.' || c == ',')
749 };
750 let is_base_form = self
751 .interner
752 .resolve(self.peek().lexeme)
753 .eq_ignore_ascii_case(self.interner.resolve(*lemma));
754 let copula_after = matches!(
755 self.tokens.get(self.current + 1).map(|t| &t.kind),
756 Some(TokenType::Is)
757 | Some(TokenType::Are)
758 | Some(TokenType::Was)
759 | Some(TokenType::Were)
760 );
761 // A base-form verb-word is a deverbal noun ONLY at the NP TAIL —
762 // a clause boundary / finite verb / copula follows. If a VP
763 // continuation follows instead (adverb, object, PP), it is the
764 // MATRIX verb and must NOT be eaten: "the goods from Spain SELL
765 // quickly" (a PP-object/nominal context, base "sell" + adverb)
766 // keeps "sell" as the verb. This is the same NP-tail test the
767 // object-boundary case below uses.
768 let next_ends_np = matches!(
769 self.tokens.get(self.current + 1).map(|t| &t.kind),
770 None | Some(TokenType::Period)
771 | Some(TokenType::EOF)
772 | Some(TokenType::Comma)
773 | Some(TokenType::And)
774 | Some(TokenType::Or)
775 | Some(TokenType::Verb { .. })
776 | Some(TokenType::Is)
777 | Some(TokenType::Are)
778 | Some(TokenType::Was)
779 | Some(TokenType::Were)
780 );
781 // A BASE-FORM verb-word after a noun head, inside a NOMINAL
782 // context (a PP object / comparative standard) and at the NP tail,
783 // is a deverbal noun-noun COMPOUND: "a cork COVER", "an amber BASE",
784 // "a tataki ROLL". The base-form gate excludes inflected matrix
785 // verbs (runs/votes/sold); the context gate keeps SUBJECT NPs out.
786 let nominal_compound = self.nominal_np_context && is_base_form && next_ends_np;
787 // A CAPITALIZED verb-word after an already MULTI-WORD proper-name
788 // head ("Bald_Hill" + "Run") is the tail of a place name, not a
789 // verb. The head MUST already be compounded (contains '_') — this
790 // is what separates a place name from a SUBJECT + matrix verb
791 // ("John" + idiom lemma "Die" → must stay John kicked-the-bucket,
792 // not John_Die). Both sides capitalized + a clause boundary after.
793 let proper_name_part = self.interner.resolve(noun).contains('_')
794 && self
795 .interner
796 .resolve(noun)
797 .chars()
798 .next()
799 .map_or(false, |c| c.is_ascii_uppercase())
800 && self
801 .interner
802 .resolve(self.peek().lexeme)
803 .chars()
804 .next()
805 .map_or(false, |c| c.is_ascii_uppercase())
806 && matches!(
807 self.tokens.get(self.current + 1).map(|t| &t.kind),
808 None | Some(TokenType::Period)
809 | Some(TokenType::EOF)
810 | Some(TokenType::Comma)
811 | Some(TokenType::And)
812 | Some(TokenType::Or)
813 );
814 // A BASE-FORM verb-word in an OBJECT/complement NP (!greedy:
815 // the clause already has its verb), NOT followed by its own
816 // argument, is a deverbal noun joining the head ("the spicy
817 // tataki ROLL", "the onion DIP"). The following token confirms
818 // it: a clause boundary, or a finite verb/copula (the matrix or
819 // next clause's verb) — both rule out a verb reading. A PRONOUN
820 // after it ("own a donkey BEAT it") is NOT a boundary, so the
821 // nuclear verb of a quantifier is left alone. Mirrors the
822 // Ambiguous arm's object_compound_boundary.
823 let object_boundary =
824 !greedy && self.filler_gap.is_none() && is_base_form && next_ends_np;
825 // A clause-final GERUND (-ing) after a noun head in an object /
826 // nominal NP is a noun-incorporation compound ("started WEIGHT
827 // LIFTING", "enjoys BIRD WATCHING") — the noun is the gerund's
828 // incorporated object. Requires the NP tail (next_ends_np) so a
829 // reduced relative with its own object ("the man lifting WEIGHTS")
830 // is untouched. Uses the SURFACE form so the compound is
831 // weight_lifting, not the lemma weight_lift.
832 let gerund_compound = (!greedy || self.nominal_np_context)
833 && self.filler_gap.is_none()
834 && self
835 .interner
836 .resolve(self.peek().lexeme)
837 .to_lowercase()
838 .ends_with("ing")
839 && next_ends_np;
840 if (head_is_numeric && is_base_form)
841 || copula_after
842 || nominal_compound
843 || proper_name_part
844 || object_boundary
845 {
846 *lemma
847 } else if gerund_compound {
848 self.peek().lexeme
849 } else {
850 break;
851 }
852 }
853 _ => break,
854 };
855 self.advance();
856 let head_str = self.interner.resolve(noun);
857 let next_str = self.interner.resolve(next);
858 let compound = format!("{}_{}", head_str, next_str);
859 noun = self.interner.intern(&compound);
860 }
861
862 // Head noun + numeric value: an instance/slot LABEL — "number 7",
863 // "room 204", "lane 3", "version 2", "exhibit 5", "car 7". This is a
864 // GENERAL grammatical pattern, not a hardcoded word list (which would
865 // never generalise to unseen clues): in English a common noun is
866 // otherwise never directly followed by a BARE number, so a head noun
867 // immediately followed by a Cardinal/Number names a specific instance —
868 // join them into one symbol. Both word-numbers ("seven") and digits ("7")
869 // apply. The one exception is a MEASURE ("a box 3 FEET tall"), where the
870 // number begins a unit phrase — a following CalendarUnit / registered unit
871 // word vetoes the label reading. Gated to declarative (NL) parsing so it
872 // never disturbs LOGOS imperative index syntax ("item 3 of arr").
873 let label_value: Option<String> = match self.peek().kind {
874 TokenType::Cardinal(n) => Some(n.to_string()),
875 TokenType::Number(sym) => Some(self.interner.resolve(sym).to_string()),
876 _ => None,
877 };
878 if let Some(value) = label_value {
879 let number_starts_measure = match self.tokens.get(self.current + 1) {
880 Some(t) => {
881 matches!(t.kind, TokenType::CalendarUnit(_))
882 || crate::lexicon::lookup_unit_dimension(
883 &self.interner.resolve(t.lexeme).to_lowercase(),
884 )
885 .is_some()
886 }
887 None => false,
888 };
889 let head_str = self.interner.resolve(noun).to_string();
890 // A numeric head ("1850") is not a label base; only a real word is.
891 let head_is_word =
892 !head_str.is_empty() && !head_str.chars().all(|c| c.is_ascii_digit());
893 // A MONTH head ("April 15") is a date, handled by the month+day rule
894 // just below — never an instance label.
895 let head_is_month = crate::lexicon::is_month(&head_str.to_lowercase());
896 if !number_starts_measure
897 && head_is_word
898 && !head_is_month
899 && self.mode == super::ParserMode::Declarative
900 {
901 self.advance();
902 noun = self.interner.intern(&format!("{}_{}", head_str, value));
903 }
904 }
905
906 // Month + day: "June 11", "May 3", "December 25" — the day (1–31) joins the
907 // month into a single date symbol ("June_11"). Month names are a closed
908 // lexical class (lexicon `months`).
909 {
910 let head_lower = self.interner.resolve(noun).to_lowercase();
911 if crate::lexicon::is_month(&head_lower) {
912 let day = match self.peek().kind {
913 TokenType::Cardinal(n) if (1..=31).contains(&n) => Some(n),
914 // A numeric day may carry an ordinal suffix ("15th", "3rd",
915 // "1st", "2nd"); strip it so "April 15th" and "April 15" name
916 // the same date ("April_15").
917 TokenType::Number(s) => {
918 let raw = self.interner.resolve(s);
919 let digits = raw.trim_end_matches(|c: char| c.is_ascii_alphabetic());
920 digits.parse::<u32>().ok().filter(|d| (1..=31).contains(d))
921 }
922 _ => None,
923 };
924 if let Some(day) = day {
925 self.advance();
926 let head_str = self.interner.resolve(noun);
927 noun = self.interner.intern(&format!("{}_{}", head_str, day));
928 // An attributive date modifies a following head noun ("the
929 // April 15th birthday" → April_15_birthday); absorb it so the
930 // real head isn't stranded.
931 while let TokenType::Noun(next) = self.peek().kind {
932 self.advance();
933 noun = self.interner.intern(&format!(
934 "{}_{}",
935 self.interner.resolve(noun),
936 self.interner.resolve(next)
937 ));
938 }
939 }
940 }
941 }
942
943 if self.check_possessive() {
944 self.advance();
945
946 let possessor = self.ctx.nps.alloc(NounPhrase {
947 definiteness,
948 adjectives: self.ctx.syms.alloc_slice(adjectives.clone()),
949 noun,
950 possessor: None,
951 pps: &[],
952 superlative: superlative_adj,
953 });
954
955 let mut possessed_noun = self.consume_content_word()?;
956 // A multi-word possessed compound noun ("Bernard's fountain pen",
957 // "Joe's yoga session") joins its consecutive nouns into one symbol,
958 // mirroring the head noun-noun compounding above.
959 while let TokenType::Noun(next) = self.peek().kind {
960 self.advance();
961 possessed_noun = self.interner.intern(&format!(
962 "{}_{}",
963 self.interner.resolve(possessed_noun),
964 self.interner.resolve(next)
965 ));
966 }
967
968 return Ok(NounPhrase {
969 definiteness: None,
970 adjectives: &[],
971 noun: possessed_noun,
972 possessor: Some(possessor),
973 pps: &[],
974 superlative: None,
975 });
976 }
977
978 let should_attach_pps = greedy || self.pp_attach_to_noun;
979
980 let mut pps: Vec<&'a LogicExpr<'a>> = Vec::new();
981 // Attributive measure-adjectives ("80 year old") are core restrictors of the
982 // head — collected before it — so they attach unconditionally, ahead of any
983 // optional trailing PPs.
984 pps.extend(measure_restrictors.iter().copied());
985
986 // An "of <measure>" restrictor ("a maximum range OF 475 ft", "a book OF
987 // 500 pages") names the head noun's measured value. It is UNAMBIGUOUSLY a
988 // noun restrictor (never an event adjunct or a partitive), so attach it
989 // even in a non-greedy object NP — otherwise "has a maximum range of 475
990 // ft" silently strands the measure.
991 loop {
992 let of_measure = self.check_of_preposition()
993 && matches!(
994 self.tokens.get(self.current + 1).map(|t| &t.kind),
995 Some(TokenType::Number(_)) | Some(TokenType::Cardinal(_))
996 );
997 if !of_measure {
998 break;
999 }
1000 let of_sym = match self.advance().kind {
1001 TokenType::Preposition(s) => s,
1002 _ => break,
1003 };
1004 let placeholder_var = self.interner.intern("_PP_SELF_");
1005 let measure = self.parse_measure_phrase()?;
1006 pps.push(
1007 self.ctx.exprs.alloc(LogicExpr::Predicate {
1008 name: of_sym,
1009 args: self
1010 .ctx
1011 .terms
1012 .alloc_slice([Term::Variable(placeholder_var), *measure]),
1013 world: None,
1014 }),
1015 );
1016 }
1017
1018 // Postposed measure-adjective "worth <measure>" ("the magnate WORTH $27
1019 // billion", "a stamp WORTH $50") — a postnominal adjective taking a measure
1020 // complement, the same Worth(x, measure) the copula complement builds. Without
1021 // this "worth" strands (TrailingTokens{Adjective}). Surface it as a restrictor
1022 // over the _PP_SELF_ placeholder so it lowers onto the NP's entity.
1023 if matches!(self.peek().kind, TokenType::Adjective(_))
1024 && self
1025 .interner
1026 .resolve(self.peek().lexeme)
1027 .eq_ignore_ascii_case("worth")
1028 && matches!(
1029 self.tokens.get(self.current + 1).map(|t| &t.kind),
1030 Some(TokenType::Number(_)) | Some(TokenType::Cardinal(_))
1031 )
1032 {
1033 let worth_sym = if let TokenType::Adjective(s) = self.peek().kind {
1034 s
1035 } else {
1036 unreachable!()
1037 };
1038 self.advance(); // "worth"
1039 let measure = self.parse_measure_phrase()?;
1040 let placeholder = self.interner.intern("_PP_SELF_");
1041 // Push directly to `pps` — the measure_restrictors → pps merge already ran
1042 // above (this is the post-head section).
1043 pps.push(
1044 self.ctx.exprs.alloc(LogicExpr::Predicate {
1045 name: worth_sym,
1046 args: self
1047 .ctx
1048 .terms
1049 .alloc_slice([Term::Variable(placeholder), *measure]),
1050 world: None,
1051 }),
1052 );
1053 }
1054
1055 if should_attach_pps {
1056 // "of" normally starts a partitive/genitive handled elsewhere, so it
1057 // is excluded here — EXCEPT "of <measure>" ("a range of 650 ft", "a
1058 // book of 500 pages"), where the of-phrase specifies the head noun's
1059 // measured value. That is a genuine restrictor, not a partitive, so
1060 // attach it as an Of(self, <measure>) PP.
1061 let of_measure_follows = |p: &Self| {
1062 p.check_of_preposition()
1063 && matches!(
1064 p.tokens.get(p.current + 1).map(|t| &t.kind),
1065 Some(TokenType::Number(_)) | Some(TokenType::Cardinal(_))
1066 )
1067 };
1068 while self.check_preposition()
1069 && (!self.check_of_preposition() || of_measure_follows(self))
1070 {
1071 let prep_token = self.advance().clone();
1072 let prep_name = if let TokenType::Preposition(sym) = prep_token.kind {
1073 sym
1074 } else {
1075 break;
1076 };
1077
1078 let placeholder_var = self.interner.intern("_PP_SELF_");
1079 if self.check_number()
1080 && !matches!(
1081 self.tokens.get(self.current + 2).map(|t| &t.kind),
1082 Some(TokenType::Noun(_)) | Some(TokenType::Ambiguous { .. })
1083 )
1084 {
1085 // Numeric PP object ("with 15 people", "at 385 degrees"):
1086 // keep the measured amount as the PP's object. A noun/ambiguous
1087 // head after the unit ("with 205 degree WATER") is instead a
1088 // measure-premodified noun, folded by the NP branch below.
1089 let measure = self.parse_measure_phrase()?;
1090 let pp_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
1091 name: prep_name,
1092 args: self
1093 .ctx
1094 .terms
1095 .alloc_slice([Term::Variable(placeholder_var), *measure]),
1096 world: None,
1097 });
1098 pps.push(pp_pred);
1099 } else if self.check_content_word()
1100 || self.check_number()
1101 || matches!(self.peek().kind, TokenType::Article(_))
1102 {
1103 // A PP object is an unambiguously NOMINAL tail, so a base-form
1104 // verb-word after its noun head is a deverbal compound ("with a
1105 // cork COVER", "with a faux leather COVER"), not a matrix verb.
1106 let saved_ctx = self.nominal_np_context;
1107 self.nominal_np_context = true;
1108 let pp_object_result = self.parse_noun_phrase(true);
1109 self.nominal_np_context = saved_ctx;
1110 let pp_object = pp_object_result?;
1111 let pp_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
1112 name: prep_name,
1113 args: self.ctx.terms.alloc_slice([
1114 Term::Variable(placeholder_var),
1115 Term::Constant(pp_object.noun),
1116 ]),
1117 world: None,
1118 });
1119 pps.push(pp_pred);
1120 // The PP object's own ADJECTIVES ("with the BLUE hat" →
1121 // With(self, Hat) ∧ Blue(Hat)) and nested restrictors ("with a
1122 // maximum range of 650 ft" → … ∧ Of(Range, 650 ft)) survive via
1123 // the shared recovery (the single source of truth for every PP
1124 // position); dropping them would be meaning loss.
1125 pps.extend(self.pp_object_modifier_preds(&pp_object));
1126 } else {
1127 break;
1128 }
1129 }
1130
1131 // Active object-gap reduced relative ("the waterfall Derrick photographed
1132 // in 1989" = the waterfall [that] Derrick photographed): a determiner-
1133 // headed NP whose head is followed by a reduced-relative subject+verb with
1134 // an EMPTY object slot (the gap is THIS head; English drops the
1135 // relativizer). The empty-object + transitive test (peek_reduced_object_relative)
1136 // is the PROPER deterministic discriminator — an overt object is apposition,
1137 // an intransitive verb has no gap. Reuse parse_relative_clause with the
1138 // `_PP_SELF_` placeholder so the clause — and its event complements ("in
1139 // 1989") — attach as a restrictor wherever the NP flows.
1140 if definiteness.is_some() && self.peek_reduced_object_relative() {
1141 let placeholder = self.interner.intern("_PP_SELF_");
1142 let rel = self.parse_relative_clause(placeholder)?;
1143 pps.push(rel);
1144 }
1145
1146 // Post-nominal "-ing" reduced relative ("the person arriving at
1147 // Paradise", "the assignment beginning in June", "the conductor
1148 // working on June 11"): a present participle after the noun is
1149 // unambiguously a reduced relative — it cannot be a finite main verb
1150 // without an auxiliary — so it restricts THIS noun phrase wherever the
1151 // NP appears (subject, standard, of-pair member, predicate nominal).
1152 // Attach as predicates over the `_PP_SELF_` placeholder (substituted
1153 // to the NP's variable when the NP is wrapped).
1154 if let TokenType::Verb { lemma, .. } = self.peek().kind {
1155 let is_ing = self
1156 .interner
1157 .resolve(self.peek().lexeme)
1158 .to_lowercase()
1159 .ends_with("ing");
1160 // A past participle followed by a "by"-agent is an unambiguous
1161 // PASSIVE reduced relative ("the bird trained BY the falconer",
1162 // "the photo published BY Wildzone") — a finite main verb is not
1163 // followed by a by-phrase in this position.
1164 let passive_by = matches!(
1165 self.tokens.get(self.current + 1).map(|t| &t.kind),
1166 Some(TokenType::Preposition(s))
1167 if self.interner.resolve(*s).eq_ignore_ascii_case("by")
1168 );
1169 // A past participle of a TRANSITIVE verb immediately followed by a
1170 // PP (no object) is a passive reduced relative ("the medicine
1171 // sourced FROM a fig", "the item made OF teak", "the flower grown
1172 // IN Olin"). Lexical transitivity disambiguates it from an
1173 // intransitive main clause ("the box arrived in April"), which a
1174 // bare common noun + PP would otherwise look like.
1175 //
1176 // The near-dead `is_transitive_verb` table (47/2623 verbs) misses
1177 // most transitives ("the gator CAUGHT in Lynn" — catch has past ==
1178 // participle, so the distinct-form rule can't save it either). In a
1179 // NOMINAL complement position (`nominal_np_context`: "X is the gator
1180 // caught in Lynn") the NP cannot be a main-clause subject, so a
1181 // past-participle + PP IS a reduced relative for any verb that is not
1182 // marked pure-intransitive — the same transitive-capable-by-default
1183 // rule the object-gap relative uses. In subject position the strict
1184 // table still gates it (keeping "The team won in 1989" a main clause).
1185 let transitive_passive = matches!(
1186 self.peek().kind,
1187 TokenType::Verb {
1188 time: crate::lexicon::Time::Past,
1189 ..
1190 }
1191 ) && matches!(
1192 self.tokens.get(self.current + 1).map(|t| &t.kind),
1193 Some(TokenType::Preposition(_))
1194 ) && (crate::lexicon::is_transitive_verb(
1195 &self.interner.resolve(lemma).to_lowercase(),
1196 ) || (self.nominal_np_context
1197 && !crate::lexicon::is_intransitive_verb(
1198 &self.interner.resolve(lemma).to_lowercase(),
1199 )));
1200 // A DISTINCT past-participle form (participle ≠ past: "grown" vs
1201 // "grew", "taken" vs "took") immediately followed by a PP is an
1202 // unambiguous passive reduced relative regardless of transitivity —
1203 // the form alone is non-finite, like "-ing" ("the flower GROWN in
1204 // Hardy", "the package TAKEN to the depot").
1205 let distinct_participle_passive = matches!(
1206 self.tokens.get(self.current + 1).map(|t| &t.kind),
1207 Some(TokenType::Preposition(_))
1208 ) && crate::lexicon::is_distinct_past_participle(
1209 &self.interner.resolve(self.peek().lexeme).to_lowercase(),
1210 );
1211 if is_ing || passive_by || transitive_passive || distinct_participle_passive {
1212 self.advance();
1213 let placeholder = self.interner.intern("_PP_SELF_");
1214 // An ACTIVE -ing reduced relative can take a DIRECT OBJECT
1215 // ("the origami DEPICTING a dragon", "the survivor BRINGING the
1216 // rope") → Participle(x, object). Only -ing (a passive
1217 // participle's patient is the head itself), and only a real
1218 // object NP (article / content word), never a preposition or
1219 // the matrix verb.
1220 let direct_obj = if is_ing
1221 && (matches!(self.peek().kind, TokenType::Article(_))
1222 || self.check_content_word())
1223 && !self.check_preposition()
1224 && !self.check_verb()
1225 {
1226 Some(self.parse_noun_phrase(true)?)
1227 } else {
1228 None
1229 };
1230 let participle_pred = if let Some(ref obj) = direct_obj {
1231 self.ctx.exprs.alloc(LogicExpr::Predicate {
1232 name: lemma,
1233 args: self.ctx.terms.alloc_slice([
1234 Term::Variable(placeholder),
1235 Term::Constant(obj.noun),
1236 ]),
1237 world: None,
1238 })
1239 } else {
1240 self.ctx.exprs.alloc(LogicExpr::Predicate {
1241 name: lemma,
1242 args: self.ctx.terms.alloc_slice([Term::Variable(placeholder)]),
1243 world: None,
1244 })
1245 };
1246 pps.push(participle_pred);
1247 // The participle's PP / directional-"to" complements. "of" is
1248 // allowed here ("made OF teak", "made OF sandalwood") — it is
1249 // the participle's material complement, not a possessive.
1250 loop {
1251 let prep = if self.check_preposition() {
1252 match self.advance().kind {
1253 TokenType::Preposition(s) => s,
1254 _ => break,
1255 }
1256 } else if self.check(&TokenType::To)
1257 && matches!(
1258 self.tokens.get(self.current + 1).map(|t| &t.kind),
1259 Some(TokenType::Article(_))
1260 | Some(TokenType::Noun(_))
1261 | Some(TokenType::ProperName(_))
1262 )
1263 {
1264 self.advance();
1265 self.interner.intern("To")
1266 } else {
1267 break;
1268 };
1269 if self.check_number() {
1270 // A numeric PP object in a reduced relative: "found IN
1271 // 1992", "sent in 1976", "donated in 2010" — keep the
1272 // year/amount, else it strands.
1273 let measure = self.parse_measure_phrase()?;
1274 pps.push(
1275 self.ctx.exprs.alloc(LogicExpr::Predicate {
1276 name: prep,
1277 args: self
1278 .ctx
1279 .terms
1280 .alloc_slice([Term::Variable(placeholder), *measure]),
1281 world: None,
1282 }),
1283 );
1284 } else if self.check_content_word()
1285 || matches!(self.peek().kind, TokenType::Article(_))
1286 {
1287 let obj = self.parse_noun_phrase(true)?;
1288 pps.push(self.ctx.exprs.alloc(LogicExpr::Predicate {
1289 name: prep,
1290 args: self.ctx.terms.alloc_slice([
1291 Term::Variable(placeholder),
1292 Term::Constant(obj.noun),
1293 ]),
1294 world: None,
1295 }));
1296 } else {
1297 break;
1298 }
1299 }
1300 }
1301 }
1302 }
1303 let pps_slice = self.ctx.pps.alloc_slice(pps);
1304
1305 if self.check_of_preposition() {
1306 // Two-Pass Type Disambiguation:
1307 // If the noun is a known generic type (e.g., "Stack", "List"),
1308 // then "X of Y" is a type instantiation, not a possessive.
1309 // For now, we still parse it as possessive structurally, but
1310 // the type_registry enables future AST extensions for type annotations.
1311 let is_generic = self.is_generic_type(noun);
1312
1313 if !is_generic {
1314 // Standard possessive: "owner of house" → possessor relationship
1315 self.advance();
1316
1317 let possessor_np = self.parse_noun_phrase(true)?;
1318 let possessor = self.ctx.nps.alloc(possessor_np);
1319
1320 return Ok(NounPhrase {
1321 definiteness,
1322 adjectives: self.ctx.syms.alloc_slice(adjectives),
1323 noun,
1324 possessor: Some(possessor),
1325 pps: pps_slice,
1326 superlative: superlative_adj,
1327 });
1328 }
1329 // If generic type, fall through to regular noun phrase handling.
1330 // The "of [Type]" will be left unparsed for now.
1331 // Future: Parse as GenericType { base: noun, params: [...] }
1332 }
1333
1334 Ok(NounPhrase {
1335 definiteness,
1336 adjectives: self.ctx.syms.alloc_slice(adjectives),
1337 noun,
1338 possessor: possessor_from_pronoun,
1339 pps: pps_slice,
1340 superlative: superlative_adj,
1341 })
1342 }
1343
1344 fn parse_noun_phrase_for_relative(&mut self) -> ParseResult<NounPhrase<'a>> {
1345 let mut definiteness = None;
1346 let mut adjectives = Vec::new();
1347
1348 if let TokenType::Article(def) = self.peek().kind {
1349 definiteness = Some(def);
1350 self.advance();
1351 }
1352
1353 loop {
1354 if self.is_at_end() {
1355 break;
1356 }
1357
1358 let is_adjective = matches!(self.peek().kind, TokenType::Adjective(_));
1359 if !is_adjective {
1360 break;
1361 }
1362
1363 let next_is_content = if self.current + 1 < self.tokens.len() {
1364 matches!(
1365 self.tokens[self.current + 1].kind,
1366 TokenType::Noun(_)
1367 | TokenType::Adjective(_)
1368 | TokenType::Verb { .. }
1369 | TokenType::ProperName(_)
1370 )
1371 } else {
1372 false
1373 };
1374
1375 if next_is_content {
1376 if let TokenType::Adjective(adj) = self.advance().kind.clone() {
1377 adjectives.push(adj);
1378 }
1379 } else {
1380 break;
1381 }
1382 }
1383
1384 let noun = self.consume_content_word_for_relative()?;
1385
1386 if self.check(&TokenType::That) || self.check(&TokenType::Who) {
1387 self.advance();
1388 let var_name = self.interner.intern(&format!("r{}", self.var_counter));
1389 self.var_counter += 1;
1390 let _nested_clause = self.parse_relative_clause(var_name)?;
1391 }
1392
1393 Ok(NounPhrase {
1394 definiteness,
1395 adjectives: self.ctx.syms.alloc_slice(adjectives),
1396 noun,
1397 possessor: None,
1398 pps: &[],
1399 superlative: None,
1400 })
1401 }
1402
1403 fn noun_phrase_to_term(&self, np: &NounPhrase<'a>) -> Term<'a> {
1404 if let Some(possessor) = np.possessor {
1405 let possessor_term = self.noun_phrase_to_term(possessor);
1406 Term::Possessed {
1407 possessor: self.ctx.terms.alloc(possessor_term),
1408 possessed: np.noun,
1409 }
1410 } else {
1411 Term::Constant(np.noun)
1412 }
1413 }
1414
1415 fn numeric_label_head(
1416 &mut self,
1417 n: i64,
1418 head: crate::intern::Symbol,
1419 definiteness: Option<Definiteness>,
1420 measure_restrictors: &mut Vec<&'a LogicExpr<'a>>,
1421 ) -> crate::intern::Symbol {
1422 // A numeric label that names a DECLARED item ("2003" registered as a
1423 // year) un-fuses: the label becomes the head noun PLUS a
1424 // P(_PP_SELF_, <number>) restrictor, converging with the
1425 // prepositional-phrase form ("the holiday was in 2003" →
1426 // Holiday(x) ∧ In(x, 2003)). The numeric term mirrors the PP form's
1427 // measure value EXACTLY so the two unify. Un-fusing is gated to definite
1428 // descriptions (a label refers); an undeclared number — or a category
1429 // that maps to no preposition — keeps the fused symbol.
1430 if definiteness == Some(Definiteness::Definite) {
1431 let item_sym = self.interner.intern(&n.to_string());
1432 if let Some(category) = self.drs.item_category(item_sym) {
1433 let cat_lemma = Self::singularize_noun(self.interner.resolve(category));
1434 if let Some(prep) = category_preposition(&cat_lemma.to_lowercase()) {
1435 let prep_sym = self.interner.intern(prep);
1436 let placeholder = self.interner.intern("_PP_SELF_");
1437 let value = Term::Value {
1438 kind: crate::ast::logic::NumberKind::Integer(n),
1439 unit: None,
1440 dimension: None,
1441 };
1442 let pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
1443 name: prep_sym,
1444 args: self
1445 .ctx
1446 .terms
1447 .alloc_slice([Term::Variable(placeholder), value]),
1448 world: None,
1449 });
1450 measure_restrictors.push(pred);
1451 return head;
1452 }
1453 }
1454 }
1455 let head_str = self.interner.resolve(head);
1456 self.interner.intern(&format!("{}_{}", n, head_str))
1457 }
1458
1459 fn consume_label_head_noun_first(&mut self) -> ParseResult<crate::intern::Symbol> {
1460 let noun_sym = if let TokenType::Ambiguous {
1461 primary,
1462 alternatives,
1463 } = &self.peek().kind
1464 {
1465 let from_primary = match **primary {
1466 TokenType::Noun(s) | TokenType::Adjective(s) => Some(s),
1467 _ => None,
1468 };
1469 from_primary.or_else(|| {
1470 alternatives.iter().find_map(|t| match t {
1471 TokenType::Noun(s) | TokenType::Adjective(s) => Some(*s),
1472 _ => None,
1473 })
1474 })
1475 } else {
1476 None
1477 };
1478 if let Some(s) = noun_sym {
1479 self.advance();
1480 return Ok(s);
1481 }
1482 self.consume_content_word()
1483 }
1484
1485 fn check_possessive(&self) -> bool {
1486 matches!(self.peek().kind, TokenType::Possessive)
1487 }
1488
1489 /// Whether the cursor is at the SUBJECT of an active object-gap reduced relative
1490 /// ("the prize | Tara won", cursor at "Tara"). The PROPER, deterministic test
1491 /// (no trial-parse): a proper-name / pronoun subject, then a TRANSITIVE verb
1492 /// (only a transitive verb has an object slot for the head to fill — an
1493 /// intransitive "the dancer Tara performed" is apposition, not a relative), then
1494 /// an EMPTY object slot — the token after the verb does NOT start a direct object
1495 /// (an overt object "the dancer Tara won THE PRIZE" is apposition, not a gap).
1496 /// The caller additionally requires a determiner-headed NP.
1497 fn peek_reduced_object_relative(&self) -> bool {
1498 if !matches!(
1499 self.peek().kind,
1500 TokenType::ProperName(_) | TokenType::Pronoun { .. }
1501 ) {
1502 return false;
1503 }
1504 // A token that would START a direct/prepositional object — its presence after
1505 // the verb means the slot is filled (apposition), so there is no gap.
1506 let starts_object = |kind: Option<&TokenType>| {
1507 kind.is_some_and(|t| t.is_generalized_quantifier())
1508 || matches!(
1509 kind,
1510 Some(TokenType::Article(_))
1511 | Some(TokenType::Noun(_))
1512 | Some(TokenType::ProperName(_))
1513 | Some(TokenType::Number(_))
1514 | Some(TokenType::Cardinal(_))
1515 | Some(TokenType::Possessive)
1516 | Some(TokenType::Pronoun { .. })
1517 | Some(TokenType::All)
1518 | Some(TokenType::Some)
1519 | Some(TokenType::No)
1520 | Some(TokenType::Any)
1521 )
1522 };
1523 // Assume transitive-CAPABLE by default (English verbs overwhelmingly are);
1524 // only a verb marked pure-intransitive has no DIRECT object slot to fill.
1525 let verb_is_intransitive = self.tokens.get(self.current + 1).map_or(true, |t| {
1526 matches!(t.kind, TokenType::Verb { lemma, .. }
1527 if crate::lexicon::is_intransitive_verb(
1528 &self.interner.resolve(lemma).to_lowercase()))
1529 });
1530 let verb_follows = matches!(
1531 self.tokens.get(self.current + 1).map(|t| &t.kind),
1532 Some(TokenType::Verb { .. })
1533 );
1534 if !verb_follows {
1535 return false;
1536 }
1537 // A STRANDED preposition after the verb ("the friend Simon went WITH", "the
1538 // animal Eva works WITH") makes the GAP the object of that preposition, so
1539 // even a pure-intransitive verb heads the relative. The preposition's own
1540 // object slot must be empty (the next token does not start an NP).
1541 let stranded_prep = matches!(
1542 self.tokens.get(self.current + 2).map(|t| &t.kind),
1543 Some(TokenType::Preposition(_))
1544 ) && !starts_object(self.tokens.get(self.current + 3).map(|t| &t.kind));
1545 if stranded_prep {
1546 return true;
1547 }
1548 // Otherwise a transitive verb with an EMPTY direct-object slot (the head is
1549 // the gap); an overt object after the verb is apposition, not a gap.
1550 if verb_is_intransitive {
1551 return false;
1552 }
1553 !starts_object(self.tokens.get(self.current + 2).map(|t| &t.kind))
1554 }
1555
1556 fn peek_definite_reduced_relative_object(&self) -> bool {
1557 // The cursor must open a DEFINITE NP.
1558 if !matches!(self.peek().kind, TokenType::Article(Definiteness::Definite)) {
1559 return false;
1560 }
1561 // Skip the article, then any adjectives, to land on the noun head.
1562 let mut p = self.current + 1;
1563 while matches!(
1564 self.tokens.get(p).map(|t| &t.kind),
1565 Some(TokenType::Adjective(_)) | Some(TokenType::NonIntersectiveAdjective(_))
1566 ) {
1567 p += 1;
1568 }
1569 // The relativized head: a common noun.
1570 if !matches!(
1571 self.tokens.get(p).map(|t| &t.kind),
1572 Some(TokenType::Noun(_))
1573 | Some(TokenType::CalendarUnit(_))
1574 | Some(TokenType::Ambiguous { .. })
1575 ) {
1576 return false;
1577 }
1578 let subj = p + 1;
1579 // The relative's overt subject is a fresh ProperName / Pronoun.
1580 if !matches!(
1581 self.tokens.get(subj).map(|t| &t.kind),
1582 Some(TokenType::ProperName(_)) | Some(TokenType::Pronoun { .. })
1583 ) {
1584 return false;
1585 }
1586 // …immediately followed by the relative's finite verb.
1587 let vp = subj + 1;
1588 if !matches!(
1589 self.tokens.get(vp).map(|t| &t.kind),
1590 Some(TokenType::Verb { .. })
1591 ) {
1592 return false;
1593 }
1594 // Either a stranded preposition (gap = its object: "the friend Simon went
1595 // WITH") or a transitive verb with an empty direct-object slot (gap = the
1596 // head: "the waterfall Derrick photographed"). A filled slot after the verb
1597 // is apposition, not a gap.
1598 let starts_object = |kind: Option<&TokenType>| {
1599 kind.is_some_and(|t| t.is_generalized_quantifier())
1600 || matches!(
1601 kind,
1602 Some(TokenType::Article(_))
1603 | Some(TokenType::Noun(_))
1604 | Some(TokenType::ProperName(_))
1605 | Some(TokenType::Number(_))
1606 | Some(TokenType::Cardinal(_))
1607 | Some(TokenType::Possessive)
1608 | Some(TokenType::Pronoun { .. })
1609 | Some(TokenType::All)
1610 | Some(TokenType::Some)
1611 | Some(TokenType::No)
1612 | Some(TokenType::Any)
1613 )
1614 };
1615 let after_verb = self.tokens.get(vp + 1).map(|t| &t.kind);
1616 if matches!(after_verb, Some(TokenType::Preposition(_)))
1617 && !starts_object(self.tokens.get(vp + 2).map(|t| &t.kind))
1618 {
1619 return true;
1620 }
1621 let verb_is_intransitive = self.tokens.get(vp).map_or(true, |t| {
1622 matches!(t.kind, TokenType::Verb { lemma, .. }
1623 if crate::lexicon::is_intransitive_verb(
1624 &self.interner.resolve(lemma).to_lowercase()))
1625 });
1626 if verb_is_intransitive {
1627 return false;
1628 }
1629 !starts_object(after_verb)
1630 }
1631
1632 fn check_of_preposition(&self) -> bool {
1633 if let TokenType::Preposition(p) = self.peek().kind {
1634 p.is(self.interner, "of")
1635 } else {
1636 false
1637 }
1638 }
1639
1640 fn check_proper_name_or_label(&self) -> bool {
1641 self.is_proper_name_or_label(&self.peek().kind)
1642 }
1643
1644 fn is_proper_name_or_label(&self, kind: &TokenType) -> bool {
1645 match kind {
1646 TokenType::ProperName(_) => true,
1647 TokenType::Noun(s) => {
1648 let str_val = self.interner.resolve(*s);
1649 str_val.len() == 1 && str_val.chars().next().unwrap().is_uppercase()
1650 }
1651 _ => false,
1652 }
1653 }
1654
1655 fn check_possessive_pronoun(&self) -> bool {
1656 match &self.peek().kind {
1657 TokenType::Pronoun {
1658 case: Case::Possessive,
1659 ..
1660 } => true,
1661 TokenType::Ambiguous {
1662 primary,
1663 alternatives,
1664 } => {
1665 let is_possessive = matches!(
1666 **primary,
1667 TokenType::Pronoun {
1668 case: Case::Possessive,
1669 ..
1670 }
1671 ) || alternatives.iter().any(|alt| {
1672 matches!(
1673 alt,
1674 TokenType::Pronoun {
1675 case: Case::Possessive,
1676 ..
1677 }
1678 )
1679 });
1680 if !is_possessive {
1681 return false;
1682 }
1683 if self.noun_priority_mode {
1684 return true;
1685 }
1686 // Outside noun-priority contexts, the possessive reading of an
1687 // object/possessive-ambiguous pronoun ("her") applies exactly
1688 // when an NP head follows: "saw her dog" vs "saw her".
1689 self.possessive_np_head_follows()
1690 }
1691 _ => false,
1692 }
1693 }
1694}