Skip to main content

logicaffeine_language/
drs.rs

1//! Discourse Representation Structure (DRS) for anaphora resolution and scope tracking.
2//!
3//! This module implements a simplified DRS following the theory developed by Hans Kamp
4//! and Uwe Reyle. The DRS tracks referents (discourse entities) across sentences and
5//! handles pronoun resolution, donkey anaphora, and quantifier scope.
6//!
7//! # Core Concepts
8//!
9//! - **Box**: A scope container holding referents and conditions. Boxes nest to form
10//!   scope islands (conditionals, quantifiers, negation).
11//! - **Referent**: A discourse entity with a variable, noun class, gender, and number.
12//!   Introduced by indefinites, proper names, or quantifiers.
13//! - **Accessibility**: Whether a referent can be accessed from a given scope.
14//!   Negation and disjunction block accessibility outward.
15//!
16//! # Key Types
17//!
18//! | Type | Purpose |
19//! |------|---------|
20//! | [`Drs`] | The box hierarchy tracking referents and their scopes |
21//! | [`WorldState`] | Unified discourse state persisting across sentences |
22//! | [`BoxType`] | Classification of scope containers (Main, Negation, Modal, etc.) |
23//! | [`Referent`] | A discourse entity with gender, number, and source information |
24//! | [`ScopeError`] | Error when pronoun resolution fails due to scope constraints |
25//!
26//! # Accessibility Rules
27//!
28//! A pronoun in box B can access referent R in box A if:
29//! 1. A is B (same box)
30//! 2. A is an ancestor of B (parent chain)
31//! 3. A is a conditional antecedent and B is the consequent of the same conditional
32//! 4. A is a universal restrictor and B is the universal scope
33//!
34//! Referents in **negation** or **disjunction** boxes are NEVER accessible from outside.
35//!
36//! # Example
37//!
38//! "If a farmer owns a donkey, he beats it."
39//! - "a farmer" introduces referent x in conditional antecedent box
40//! - "a donkey" introduces referent y in conditional antecedent box
41//! - "he" resolves to x (accessible from consequent)
42//! - "it" resolves to y (accessible from consequent)
43//! - Both receive universal quantification due to conditional DRS signature
44
45use logicaffeine_base::Symbol;
46use std::fmt;
47
48// Re-export lexicon types for DRS usage
49pub use logicaffeine_lexicon::types::{Case, Gender, Number};
50
51// ============================================
52// CORE DISCOURSE TYPES (moved from context.rs)
53// ============================================
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum TimeRelation {
57    Precedes,
58    Equals,
59}
60
61#[derive(Debug, Clone)]
62pub struct TimeConstraint {
63    pub left: String,
64    pub relation: TimeRelation,
65    pub right: String,
66}
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
69pub enum OwnershipState {
70    #[default]
71    Owned,
72    Moved,
73    Borrowed,
74}
75
76// ============================================
77// SCOPE ERROR TYPES
78// ============================================
79
80/// Error when pronoun resolution fails due to scope constraints
81#[derive(Debug, Clone, PartialEq)]
82pub enum ScopeError {
83    /// Referent exists but is trapped in an inaccessible scope
84    InaccessibleReferent {
85        gender: Gender,
86        blocking_scope: BoxType,
87        reason: String,
88    },
89    /// No matching referent found at all
90    NoMatchingReferent { gender: Gender, number: Number },
91}
92
93impl fmt::Display for ScopeError {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        match self {
96            ScopeError::InaccessibleReferent {
97                gender,
98                blocking_scope,
99                reason,
100            } => {
101                write!(
102                    f,
103                    "Cannot resolve {:?} pronoun: referent is trapped in {:?} scope. {}",
104                    gender, blocking_scope, reason
105                )
106            }
107            ScopeError::NoMatchingReferent { gender, number } => {
108                write!(
109                    f,
110                    "Cannot resolve {:?} {:?} pronoun: no matching referent in accessible scope",
111                    gender, number
112                )
113            }
114        }
115    }
116}
117
118impl std::error::Error for ScopeError {}
119
120// ============================================
121// TELESCOPE SUPPORT
122// ============================================
123
124/// Path segment for navigating to insertion point during AST restructuring
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126pub enum ScopePath {
127    /// Enter body of ∀ or ∃ quantifier
128    QuantifierBody,
129    /// Enter consequent of → implication
130    ImplicationRight,
131    /// Enter right side of ∧ conjunction
132    ConjunctionRight,
133}
134
135/// A referent that may be accessed via telescoping across sentence boundaries
136#[derive(Debug, Clone)]
137pub struct TelescopeCandidate {
138    pub variable: Symbol,
139    pub noun_class: Symbol,
140    pub gender: Gender,
141    /// The box index where this referent was introduced
142    pub origin_box: usize,
143    /// Path to navigate AST for scope extension
144    pub scope_path: Vec<ScopePath>,
145    /// Whether this referent was introduced in a modal scope
146    pub in_modal_scope: bool,
147}
148
149// ============================================
150// MODAL SUBORDINATION SUPPORT
151// ============================================
152
153/// Modal context for tracking hypothetical worlds across sentences.
154/// Enables modal subordination: "A wolf might walk in. It would eat you."
155#[derive(Debug, Clone)]
156pub struct ModalContext {
157    /// Whether we're currently inside a modal scope
158    pub active: bool,
159    /// The modal flavor (epistemic vs root)
160    pub is_epistemic: bool,
161    /// Force value (0.0 = impossibility, 1.0 = necessity)
162    pub force: f32,
163}
164
165// ============================================
166// WORLD STATE (Unified Discourse State)
167// ============================================
168
169/// The unified discourse state that persists across sentences.
170#[derive(Debug, Clone)]
171pub struct WorldState {
172    /// The global DRS (box hierarchy for scope tracking)
173    pub drs: Drs,
174    /// Event variable counter (e1, e2, e3...)
175    event_counter: usize,
176    /// Event history for temporal ordering
177    event_history: Vec<String>,
178    /// Reference time counter (r1, r2, r3...)
179    reference_time_counter: usize,
180    /// Current reference time
181    current_reference_time: Option<String>,
182    /// Temporal constraints between events
183    time_constraints: Vec<TimeConstraint>,
184    /// Telescope candidates from previous sentence
185    telescope_candidates: Vec<TelescopeCandidate>,
186    /// Whether we're in discourse mode (processing multi-sentence discourse)
187    /// When true, unresolved pronouns should error instead of deictic fallback
188    discourse_mode: bool,
189    /// Current modal context (if any) for tracking modal scope
190    current_modal_context: Option<ModalContext>,
191    /// Modal context from previous sentence for subordination
192    prior_modal_context: Option<ModalContext>,
193}
194
195impl WorldState {
196    pub fn new() -> Self {
197        Self {
198            drs: Drs::new(),
199            event_counter: 0,
200            event_history: Vec::new(),
201            reference_time_counter: 0,
202            current_reference_time: None,
203            time_constraints: Vec::new(),
204            telescope_candidates: Vec::new(),
205            discourse_mode: false,
206            current_modal_context: None,
207            prior_modal_context: None,
208        }
209    }
210
211    /// Generate next event variable (e1, e2, e3...)
212    pub fn next_event_var(&mut self) -> String {
213        self.event_counter += 1;
214        let var = format!("e{}", self.event_counter);
215        self.event_history.push(var.clone());
216        var
217    }
218
219    /// Get event history for temporal ordering
220    pub fn event_history(&self) -> &[String] {
221        &self.event_history
222    }
223
224    /// Generate next reference time (r1, r2, r3...)
225    pub fn next_reference_time(&mut self) -> String {
226        self.reference_time_counter += 1;
227        let var = format!("r{}", self.reference_time_counter);
228        self.current_reference_time = Some(var.clone());
229        var
230    }
231
232    /// Get current reference time
233    pub fn current_reference_time(&self) -> String {
234        self.current_reference_time
235            .clone()
236            .unwrap_or_else(|| "S".to_string())
237    }
238
239    /// Add a temporal constraint
240    pub fn add_time_constraint(&mut self, left: String, relation: TimeRelation, right: String) {
241        self.time_constraints.push(TimeConstraint {
242            left,
243            relation,
244            right,
245        });
246    }
247
248    /// Get all time constraints
249    pub fn time_constraints(&self) -> &[TimeConstraint] {
250        &self.time_constraints
251    }
252
253    /// Clear time constraints (for sentence boundary reset if needed)
254    pub fn clear_time_constraints(&mut self) {
255        self.time_constraints.clear();
256        self.reference_time_counter = 0;
257        self.current_reference_time = None;
258    }
259
260    /// Mark a sentence boundary - collect telescope candidates
261    pub fn end_sentence(&mut self) {
262        // Collect referents that can telescope from current DRS state
263        let mut candidates = self.drs.get_telescope_candidates();
264
265        // MODAL BARRIER: If this sentence had a modal, mark ALL its referents as modal-sourced.
266        // This handles "A wolf might enter" where the wolf is introduced BEFORE we see "might".
267        // The wolf should be marked as hypothetical even though it's in the main DRS box.
268        if self.current_modal_context.is_some() {
269            for candidate in &mut candidates {
270                candidate.in_modal_scope = true;
271            }
272        }
273
274        self.telescope_candidates = candidates;
275        // Capture modal context for subordination in next sentence
276        self.prior_modal_context = self.current_modal_context.take();
277        // Mark that we're now in discourse mode (multi-sentence context)
278        self.discourse_mode = true;
279    }
280
281    /// Check if we're in discourse mode (multi-sentence context)
282    /// In discourse mode, unresolved pronouns should error instead of deictic fallback
283    pub fn in_discourse_mode(&self) -> bool {
284        self.discourse_mode
285    }
286
287    /// Get telescope candidates from previous sentence
288    pub fn telescope_candidates(&self) -> &[TelescopeCandidate] {
289        &self.telescope_candidates
290    }
291
292    /// Try to resolve a pronoun via telescoping
293    pub fn resolve_via_telescope(&mut self, gender: Gender) -> Option<TelescopeCandidate> {
294        // MODAL BARRIER: Check if we can access hypothetical entities
295        // Reality (indicative) cannot see into imagination (modal scope)
296        // Only modal subordination (e.g., "would" following "might") can access modal candidates
297        let can_access_modal = self.in_modal_context();
298
299        #[cfg(debug_assertions)]
300        // Apply same Gender Accommodation rules as resolve_pronoun:
301        // - Exact match (Male=Male, Female=Female, etc)
302        // - Unknown referent matches any pronoun (Gender Accommodation)
303        // - Unknown pronoun matches any referent
304        for candidate in &self.telescope_candidates {
305            // MODAL BARRIER CHECK: Skip hypothetical entities when in reality mode
306            if candidate.in_modal_scope && !can_access_modal {
307                // Wolf in imagination cannot be referenced from reality
308                #[cfg(debug_assertions)]
309                continue;
310            }
311
312            let gender_match = candidate.gender == gender
313                || candidate.gender == Gender::Unknown  // Gender Accommodation
314                || gender == Gender::Unknown;
315
316            if gender_match {
317                return Some(candidate.clone());
318            }
319        }
320
321        None
322    }
323
324    /// Set ownership state for a referent by noun class
325    pub fn set_ownership(&mut self, noun_class: Symbol, state: OwnershipState) {
326        self.drs.set_ownership(noun_class, state);
327    }
328
329    /// Get ownership state for a referent by noun class
330    pub fn get_ownership(&self, noun_class: Symbol) -> Option<OwnershipState> {
331        self.drs.get_ownership(noun_class)
332    }
333
334    /// Set ownership state for a referent by variable name
335    pub fn set_ownership_by_var(&mut self, var: Symbol, state: OwnershipState) {
336        self.drs.set_ownership_by_var(var, state);
337    }
338
339    /// Get ownership state for a referent by variable name
340    pub fn get_ownership_by_var(&self, var: Symbol) -> Option<OwnershipState> {
341        self.drs.get_ownership_by_var(var)
342    }
343
344    // ============================================
345    // MODAL SUBORDINATION METHODS
346    // ============================================
347
348    /// Enter a modal context (e.g., "might", "would", "could")
349    pub fn enter_modal_context(&mut self, is_epistemic: bool, force: f32) {
350        self.current_modal_context = Some(ModalContext {
351            active: true,
352            is_epistemic,
353            force,
354        });
355        // Also enter a modal box in the DRS
356        self.drs.enter_box(BoxType::ModalScope);
357    }
358
359    /// Exit the current modal context
360    pub fn exit_modal_context(&mut self) {
361        self.current_modal_context = None;
362        self.drs.exit_box();
363    }
364
365    /// Check if we're currently in a modal context
366    pub fn in_modal_context(&self) -> bool {
367        self.current_modal_context.is_some()
368    }
369
370    /// Check if there's a prior modal context for subordination
371    pub fn has_prior_modal_context(&self) -> bool {
372        self.prior_modal_context.is_some()
373    }
374
375    /// Check if current modal can subordinate to prior context
376    /// "would" can continue a "might" world
377    pub fn can_subordinate(&self) -> bool {
378        self.prior_modal_context.is_some()
379    }
380
381    /// Clear the world state (reset for new discourse)
382    pub fn clear(&mut self) {
383        self.drs.clear();
384        self.event_counter = 0;
385        self.event_history.clear();
386        self.reference_time_counter = 0;
387        self.current_reference_time = None;
388        self.time_constraints.clear();
389        self.telescope_candidates.clear();
390        self.discourse_mode = false;
391        self.current_modal_context = None;
392        self.prior_modal_context = None;
393    }
394}
395
396impl Default for WorldState {
397    fn default() -> Self {
398        Self::new()
399    }
400}
401
402// ============================================
403// REFERENT SOURCE
404// ============================================
405
406#[derive(Debug, Clone, Copy, PartialEq, Eq)]
407pub enum ReferentSource {
408    /// Indefinite in main clause - gets existential force
409    MainClause,
410    /// Proper name - no quantifier (constant)
411    ProperName,
412    /// Indefinite in conditional antecedent - gets universal force (DRS signature)
413    ConditionalAntecedent,
414    /// Indefinite in universal restrictor (relative clause) - gets universal force
415    UniversalRestrictor,
416    /// Inside negation scope - inaccessible outward
417    NegationScope,
418    /// Inside disjunction - inaccessible outward
419    Disjunct,
420    /// Inside modal scope - accessible via modal subordination
421    ModalScope,
422}
423
424impl ReferentSource {
425    pub fn gets_universal_force(&self) -> bool {
426        matches!(
427            self,
428            ReferentSource::ConditionalAntecedent | ReferentSource::UniversalRestrictor
429        )
430    }
431}
432
433#[derive(Debug, Clone, Copy, PartialEq, Eq)]
434pub enum BoxType {
435    /// Top-level discourse box
436    Main,
437    /// Antecedent of conditional ("if" clause)
438    ConditionalAntecedent,
439    /// Consequent of conditional ("then" clause)
440    ConditionalConsequent,
441    /// Scope of negation
442    NegationScope,
443    /// Restrictor of universal quantifier (relative clause in "every X who...")
444    UniversalRestrictor,
445    /// Nuclear scope of universal quantifier
446    UniversalScope,
447    /// Branch of disjunction
448    Disjunct,
449    /// Scope of modal operator (might, would, could, etc.)
450    /// Allows modal subordination: pronouns can access referents via telescoping
451    ModalScope,
452}
453
454impl BoxType {
455    pub fn to_referent_source(&self) -> ReferentSource {
456        match self {
457            BoxType::Main => ReferentSource::MainClause,
458            BoxType::ConditionalAntecedent => ReferentSource::ConditionalAntecedent,
459            BoxType::ConditionalConsequent => ReferentSource::MainClause,
460            BoxType::NegationScope => ReferentSource::NegationScope,
461            BoxType::UniversalRestrictor => ReferentSource::UniversalRestrictor,
462            BoxType::UniversalScope => ReferentSource::MainClause,
463            BoxType::Disjunct => ReferentSource::Disjunct,
464            BoxType::ModalScope => ReferentSource::ModalScope,
465        }
466    }
467
468    /// Can referents in this box be accessed via telescoping across sentence boundaries?
469    /// Universal quantifiers, conditionals, and modals CAN telescope.
470    /// Negation and disjunction CANNOT telescope.
471    pub fn can_telescope(&self) -> bool {
472        matches!(
473            self,
474            BoxType::Main
475                | BoxType::UniversalScope
476                | BoxType::UniversalRestrictor
477                | BoxType::ConditionalConsequent
478                | BoxType::ConditionalAntecedent
479                | BoxType::ModalScope // Modal subordination allows cross-sentence access
480        )
481        // NegationScope and Disjunct return false implicitly
482    }
483
484    /// Does this box type block accessibility from outside?
485    pub fn blocks_accessibility(&self) -> bool {
486        matches!(self, BoxType::NegationScope | BoxType::Disjunct)
487    }
488}
489
490/// Two modifier sets match when they contain exactly the same symbols
491/// (order-independent). A description with NO modifier never matches one WITH a
492/// modifier — the distinguishing modifier is what does the referring.
493fn modifier_sets_match(a: &[Symbol], b: &[Symbol]) -> bool {
494    if a.len() != b.len() || a.is_empty() {
495        return false;
496    }
497    a.iter().all(|m| b.contains(m)) && b.iter().all(|m| a.contains(m))
498}
499
500#[derive(Debug, Clone)]
501pub struct Referent {
502    pub variable: Symbol,
503    pub noun_class: Symbol,
504    pub gender: Gender,
505    pub number: Number,
506    pub source: ReferentSource,
507    pub used_by_pronoun: bool,
508    pub ownership: OwnershipState,
509    /// The distinguishing modifier(s) of the description that introduced this
510    /// referent — the adjective/gerund that does the REFERRING in "the
511    /// \[modifier\] \[head\]". For "the hunting vacation" this holds `Hunt`. Empty
512    /// for bare descriptions ("the vacation"). Used by context-driven
513    /// coreference: two definite descriptions that share their distinguishing
514    /// modifier AND have sort-compatible head nouns denote the same entity.
515    pub modifiers: Vec<Symbol>,
516    /// An event the clause's verb introduced, not an individual: a pronoun reaches for an
517    /// individual first ("If a dog barks, IT runs" is the dog, not the barking).
518    pub is_event: bool,
519}
520
521impl Referent {
522    pub fn new(
523        variable: Symbol,
524        noun_class: Symbol,
525        gender: Gender,
526        number: Number,
527        source: ReferentSource,
528    ) -> Self {
529        Self {
530            variable,
531            noun_class,
532            gender,
533            number,
534            source,
535            used_by_pronoun: false,
536            ownership: OwnershipState::Owned,
537            modifiers: Vec::new(),
538            is_event: false,
539        }
540    }
541
542    /// Construct a referent carrying its distinguishing modifier(s).
543    pub fn with_modifiers(
544        variable: Symbol,
545        noun_class: Symbol,
546        gender: Gender,
547        number: Number,
548        source: ReferentSource,
549        modifiers: Vec<Symbol>,
550    ) -> Self {
551        let mut referent = Self::new(variable, noun_class, gender, number, source);
552        referent.modifiers = modifiers;
553        referent
554    }
555
556    pub fn should_be_universal(&self) -> bool {
557        self.source.gets_universal_force() || self.used_by_pronoun
558    }
559}
560
561#[derive(Debug, Clone, Default)]
562pub struct DrsBox {
563    pub universe: Vec<Referent>,
564    pub box_type: Option<BoxType>,
565    pub parent: Option<usize>,
566}
567
568/// A point in the DRS's growth: the box the parse was in, and how many referents each box then
569/// held. A parse that backtracks rewinds to it, so a referent registered on an abandoned path
570/// does not outlive the path — no pronoun finds it, and no conditional quantifies over it.
571#[derive(Debug, Clone)]
572pub struct DrsMark {
573    current_box: usize,
574    universes: Vec<usize>,
575}
576
577impl DrsBox {
578    pub fn new(box_type: BoxType, parent: Option<usize>) -> Self {
579        Self {
580            universe: Vec::new(),
581            box_type: Some(box_type),
582            parent,
583        }
584    }
585}
586
587#[derive(Debug, Clone)]
588pub struct Drs {
589    boxes: Vec<DrsBox>,
590    main_box: usize,
591    current_box: usize,
592    /// Maps a declared ITEM to the CATEGORY noun it was declared under. A
593    /// category declaration ("2001, 2002, 2003, and 2004 are four different
594    /// years.") records `2001 → Year`, `2002 → Year`, … so a later definite
595    /// LABEL ("the 2003 holiday") can recover the item's category and un-fuse
596    /// to the SAME relation the prepositional-phrase form produces ("the
597    /// holiday was in 2003" → In(x, 2003)). Persisting in the shared discourse
598    /// DRS is what makes the two surface forms converge across sentences.
599    item_categories: std::collections::HashMap<Symbol, Symbol>,
600}
601
602impl Drs {
603    pub fn new() -> Self {
604        let main = DrsBox::new(BoxType::Main, None);
605        Self {
606            boxes: vec![main],
607            main_box: 0,
608            current_box: 0,
609            item_categories: std::collections::HashMap::new(),
610        }
611    }
612
613    pub fn enter_box(&mut self, box_type: BoxType) -> usize {
614        let parent = self.current_box;
615        let new_box = DrsBox::new(box_type, Some(parent));
616        let idx = self.boxes.len();
617        self.boxes.push(new_box);
618        self.current_box = idx;
619        idx
620    }
621
622    pub fn exit_box(&mut self) {
623        if let Some(parent) = self.boxes[self.current_box].parent {
624            self.current_box = parent;
625        }
626    }
627
628    /// The DRS as it stands, for a speculative parse to rewind to.
629    pub fn mark(&self) -> DrsMark {
630        DrsMark {
631            current_box: self.current_box,
632            universes: self.boxes.iter().map(|b| b.universe.len()).collect(),
633        }
634    }
635
636    /// Undo what an abandoned parse added since `mark`: the boxes it opened, the referents it
637    /// introduced, and the box it was in.
638    pub fn rewind(&mut self, mark: &DrsMark) {
639        self.boxes.truncate(mark.universes.len());
640        for (drs_box, &len) in self.boxes.iter_mut().zip(&mark.universes) {
641            drs_box.universe.truncate(len);
642        }
643        self.current_box = mark.current_box;
644    }
645
646    pub fn current_box_index(&self) -> usize {
647        self.current_box
648    }
649
650    pub fn current_box_type(&self) -> Option<BoxType> {
651        self.boxes.get(self.current_box).and_then(|b| b.box_type)
652    }
653
654    pub fn introduce_referent(
655        &mut self,
656        variable: Symbol,
657        noun_class: Symbol,
658        gender: Gender,
659        number: Number,
660    ) {
661        let source = self.boxes[self.current_box]
662            .box_type
663            .map(|bt| bt.to_referent_source())
664            .unwrap_or(ReferentSource::MainClause);
665
666        let referent = Referent::new(variable, noun_class, gender, number, source);
667        self.boxes[self.current_box].universe.push(referent);
668    }
669
670    /// Introduce the event a verb describes, so a conditional antecedent gives it universal
671    /// force like any referent of its box.
672    pub fn introduce_event_referent(&mut self, variable: Symbol, event_class: Symbol) {
673        self.introduce_referent(variable, event_class, Gender::Neuter, Number::Singular);
674        if let Some(event) = self.boxes[self.current_box].universe.last_mut() {
675            event.is_event = true;
676        }
677    }
678
679    /// Introduce a referent with an explicit source (used for negative quantifiers like "No X")
680    pub fn introduce_referent_with_source(
681        &mut self,
682        variable: Symbol,
683        noun_class: Symbol,
684        gender: Gender,
685        number: Number,
686        source: ReferentSource,
687    ) {
688        let referent = Referent::new(variable, noun_class, gender, number, source);
689        self.boxes[self.current_box].universe.push(referent);
690    }
691
692    /// Introduce a referent carrying its distinguishing modifier(s) (the
693    /// adjective/gerund that does the referring in "the \[modifier\] \[head\]").
694    /// These modifiers feed context-driven coreference for definite
695    /// descriptions — see [`Drs::resolve_definite_by_modifier`].
696    pub fn introduce_referent_with_modifiers(
697        &mut self,
698        variable: Symbol,
699        noun_class: Symbol,
700        gender: Gender,
701        number: Number,
702        source: ReferentSource,
703        modifiers: Vec<Symbol>,
704    ) {
705        let referent =
706            Referent::with_modifiers(variable, noun_class, gender, number, source, modifiers);
707        self.boxes[self.current_box].universe.push(referent);
708    }
709
710    /// Accommodate a referent at the MAIN (highest) box. Definites presuppose
711    /// existence, so they project globally even when first mentioned inside
712    /// an embedded box (Van der Sandt global accommodation).
713    pub fn introduce_referent_global(
714        &mut self,
715        variable: Symbol,
716        noun_class: Symbol,
717        gender: Gender,
718        number: Number,
719        source: ReferentSource,
720    ) {
721        let referent = Referent::new(variable, noun_class, gender, number, source);
722        self.boxes[self.main_box].universe.push(referent);
723    }
724
725    pub fn introduce_proper_name(&mut self, variable: Symbol, name: Symbol, gender: Gender) {
726        // Proper names are always singular
727        let referent = Referent::new(
728            variable,
729            name,
730            gender,
731            Number::Singular,
732            ReferentSource::ProperName,
733        );
734        self.boxes[self.current_box].universe.push(referent);
735    }
736
737    /// Is this symbol a RIGID referent (proper name or deictic constant)?
738    /// A pronoun resolving to a rigid referent denotes the constant itself,
739    /// not a discourse-bound variable.
740    pub fn is_rigid_referent(&self, symbol: Symbol) -> bool {
741        self.boxes.iter().any(|b| {
742            b.universe
743                .iter()
744                .any(|r| r.variable == symbol && r.source == ReferentSource::ProperName)
745        })
746    }
747
748    /// Record that `item` was declared under category noun `category`. Called
749    /// for each member of a coordinated category declaration; read back by a
750    /// definite-description label to drive category-based un-fusing.
751    pub fn register_item_category(&mut self, item: Symbol, category: Symbol) {
752        self.item_categories.insert(item, category);
753    }
754
755    /// The category noun `item` was declared under, if any.
756    pub fn item_category(&self, item: Symbol) -> Option<Symbol> {
757        self.item_categories.get(&item).copied()
758    }
759
760    /// Check if a referent in box `from_box` can access referents in box `target_box`
761    pub fn is_accessible(&self, target_box: usize, from_box: usize) -> bool {
762        if target_box == from_box {
763            return true;
764        }
765
766        let target = &self.boxes[target_box];
767        let from = &self.boxes[from_box];
768
769        // Check target box type - some boxes block outward access
770        // The "accessibility" principle in DRT:
771        // - Reality cannot see into hypotheticals (ModalScope)
772        // - Affirmative cannot see into negative (NegationScope)
773        // - One disjunct cannot see into another (Disjunct)
774        if let Some(bt) = target.box_type {
775            match bt {
776                BoxType::NegationScope | BoxType::Disjunct | BoxType::ModalScope => {
777                    // These boxes are NOT accessible from outside
778                    // A wolf in imagination cannot be seen from reality
779                    return false;
780                }
781                _ => {}
782            }
783        }
784
785        // Check if from_box can see target_box
786        // Consequent can see antecedent
787        if let (Some(BoxType::ConditionalConsequent), Some(BoxType::ConditionalAntecedent)) =
788            (from.box_type, target.box_type)
789        {
790            // Check if they share the same parent (same conditional)
791            if from.parent == target.parent {
792                return true;
793            }
794        }
795
796        // Universal scope can see universal restrictor
797        if let (Some(BoxType::UniversalScope), Some(BoxType::UniversalRestrictor)) =
798            (from.box_type, target.box_type)
799        {
800            if from.parent == target.parent {
801                return true;
802            }
803        }
804
805        // Can always access ancestors (parent chain)
806        let mut current = from_box;
807        while let Some(parent) = self.boxes[current].parent {
808            if parent == target_box {
809                return true;
810            }
811            current = parent;
812        }
813
814        false
815    }
816
817    /// Resolve a pronoun by finding accessible referents matching gender and number
818    pub fn resolve_pronoun(
819        &mut self,
820        from_box: usize,
821        gender: Gender,
822        number: Number,
823    ) -> Result<Symbol, ScopeError> {
824        // Phase 1: Search accessible referents
825        // A referent is accessible if:
826        //   - It's in an accessible box, OR
827        //   - It has MainClause/ProperName source (globally accessible, e.g. definite descriptions)
828        // Skip referents from NegationScope or Disjunct sources (always inaccessible)
829        let mut candidates = Vec::new();
830
831        for (box_idx, drs_box) in self.boxes.iter().enumerate() {
832            let box_accessible = self.is_accessible(box_idx, from_box);
833
834            for referent in &drs_box.universe {
835                // Skip referents that are from negative quantifiers (No X) or disjuncts
836                // Both are inaccessible outward per DRS accessibility
837                if matches!(
838                    referent.source,
839                    ReferentSource::NegationScope | ReferentSource::Disjunct
840                ) {
841                    continue;
842                }
843
844                // Check if this referent is accessible:
845                // Either the box is accessible, or the referent has globally accessible source
846                let has_global_source = matches!(
847                    referent.source,
848                    ReferentSource::MainClause | ReferentSource::ProperName
849                );
850                if !box_accessible && !has_global_source {
851                    continue;
852                }
853
854                // Gender matching rules:
855                // - Exact match (Male=Male, Female=Female, etc)
856                // - Unknown referents match any pronoun (gender accommodation)
857                // - Unknown pronouns match any referent
858                // This allows "He" to refer to "farmer" even if farmer's gender is Unknown
859                let gender_match = referent.gender == gender
860                    || referent.gender == Gender::Unknown
861                    || gender == Gender::Unknown;
862
863                // Number matching: must match exactly (no number accommodation)
864                let number_match = referent.number == number;
865
866                if gender_match && number_match {
867                    // Agreement the pronoun names outright ("he" for John), not accommodates.
868                    let exact = gender != Gender::Unknown && referent.gender == gender;
869                    let rank = if referent.is_event {
870                        2
871                    } else if exact {
872                        0
873                    } else {
874                        1
875                    };
876                    candidates.push((box_idx, referent.variable, rank));
877                }
878            }
879        }
880
881        // An individual whose gender the pronoun names, then one whose gender it accommodates,
882        // then an event — and within a rank, the most recent.
883        let chosen = candidates
884            .iter()
885            .rev()
886            .min_by_key(|(_, _, rank)| *rank)
887            .map(|(box_idx, var, _)| (*box_idx, *var));
888        if let Some((box_idx, var)) = chosen {
889            for referent in &mut self.boxes[box_idx].universe {
890                if referent.variable == var {
891                    referent.used_by_pronoun = true;
892                    return Ok(var);
893                }
894            }
895        }
896
897        // Phase 2: Check inaccessible boxes OR referents with NegationScope/Disjunct source
898        // Use the same strict gender matching for consistency
899        for (_box_idx, drs_box) in self.boxes.iter().enumerate() {
900            for referent in &drs_box.universe {
901                // Referents with MainClause or ProperName source are ALWAYS accessible
902                // (definite descriptions presuppose existence and are globally accessible)
903                if matches!(
904                    referent.source,
905                    ReferentSource::MainClause | ReferentSource::ProperName
906                ) {
907                    continue;
908                }
909
910                // Check for referents with NegationScope/Disjunct source (from "No X" or disjuncts)
911                // OR referents in inaccessible boxes
912                let is_inaccessible = matches!(
913                    referent.source,
914                    ReferentSource::NegationScope | ReferentSource::Disjunct
915                ) || !self.is_accessible(_box_idx, from_box);
916
917                if is_inaccessible {
918                    // Same matching as Phase 1
919                    let gender_match = referent.gender == gender
920                        || (gender == Gender::Unknown)
921                        || (gender == Gender::Neuter && referent.gender == Gender::Unknown);
922                    let number_match = referent.number == number;
923
924                    if gender_match && number_match {
925                        // Found a matching referent but it's inaccessible
926                        let blocking_scope =
927                            if matches!(referent.source, ReferentSource::NegationScope) {
928                                BoxType::NegationScope
929                            } else if matches!(referent.source, ReferentSource::Disjunct) {
930                                BoxType::Disjunct
931                            } else {
932                                drs_box.box_type.unwrap_or(BoxType::Main)
933                            };
934                        let noun_class_str = format!("{:?}", referent.noun_class);
935                        return Err(ScopeError::InaccessibleReferent {
936                            gender,
937                            blocking_scope,
938                            reason: format!(
939                                "'{}' is trapped in {:?} scope and cannot be accessed",
940                                noun_class_str, blocking_scope
941                            ),
942                        });
943                    }
944                }
945            }
946        }
947
948        // Phase 3: Not found anywhere
949        Err(ScopeError::NoMatchingReferent { gender, number })
950    }
951
952    /// Resolve a definite description by finding accessible referent matching noun class
953    pub fn resolve_definite(&self, from_box: usize, noun_class: Symbol) -> Option<Symbol> {
954        for (box_idx, drs_box) in self.boxes.iter().enumerate() {
955            if self.is_accessible(box_idx, from_box) {
956                for referent in drs_box.universe.iter().rev() {
957                    if referent.noun_class == noun_class {
958                        return Some(referent.variable);
959                    }
960                }
961            }
962        }
963        None
964    }
965
966    /// Context-driven coreference for MODIFIED definite descriptions.
967    ///
968    /// When an exact head-noun match fails, two definite descriptions still
969    /// corefer when (a) their distinguishing modifier matches AND (b) their
970    /// head nouns are of a COMPATIBLE occasion sort. This is the
971    /// modifier-does-the-referring principle: in "the hunting vacation" /
972    /// "the hunting trip" the modifier `Hunt` identifies the entity and the
973    /// head noun (vacation/trip) is a soft type, so both descriptions denote
974    /// the same discourse referent.
975    ///
976    /// This is NOT synonymy — no `Vacation ↔ Trip` axiom is asserted; the FOL
977    /// keeps `Vacation(x)` and `Trip(x)` literally. Coreference is purely a
978    /// referent-resolution step: the later description reuses the earlier
979    /// referent's variable.
980    ///
981    /// Guardrails (enforced here):
982    /// - The modifier sets must match EXACTLY (differing modifiers — "the
983    ///   hunting trip" vs "the skydiving trip" — never corefer), and a bare
984    ///   (modifier-less) description never coreferes through this path.
985    /// - BOTH head nouns must be of an OCCASION sort (`Sort::is_occasion`)
986    ///   and mutually sort-compatible. Concrete objects ("the red box" / "the
987    ///   red ball", both `Physical`) are excluded, so a shared modifier on
988    ///   non-occasion nouns never triggers coreference.
989    pub fn resolve_definite_by_modifier(
990        &self,
991        interner: &crate::Interner,
992        from_box: usize,
993        noun_class: Symbol,
994        modifiers: &[Symbol],
995    ) -> Option<Symbol> {
996        use crate::lexicon::lookup_sort;
997
998        // A modifier-less description cannot refer through its (absent)
999        // modifier. Conservative: no modifier ⇒ no coreference via this path.
1000        if modifiers.is_empty() {
1001            return None;
1002        }
1003
1004        // The new description's head noun must itself be an occasion sort —
1005        // otherwise the modifier-does-the-referring principle does not apply.
1006        let new_sort = lookup_sort(interner.resolve(noun_class))?;
1007        if !new_sort.is_occasion() {
1008            return None;
1009        }
1010
1011        for (box_idx, drs_box) in self.boxes.iter().enumerate() {
1012            if !self.is_accessible(box_idx, from_box) {
1013                continue;
1014            }
1015            for referent in drs_box.universe.iter().rev() {
1016                // The distinguishing modifier(s) must match exactly. Order is
1017                // irrelevant; the set of modifier symbols must be equal.
1018                if !modifier_sets_match(&referent.modifiers, modifiers) {
1019                    continue;
1020                }
1021
1022                // The prior referent's head noun must also be an occasion sort
1023                // and mutually sort-compatible with the new description's head.
1024                let Some(prior_sort) = lookup_sort(interner.resolve(referent.noun_class)) else {
1025                    continue;
1026                };
1027                if !prior_sort.is_occasion() {
1028                    continue;
1029                }
1030                if !new_sort.is_compatible_with(prior_sort)
1031                    && !prior_sort.is_compatible_with(new_sort)
1032                {
1033                    continue;
1034                }
1035
1036                return Some(referent.variable);
1037            }
1038        }
1039        None
1040    }
1041
1042    /// Check if a referent exists by variable name (for imperative mode variable validation)
1043    pub fn has_referent_by_variable(&self, var: Symbol) -> bool {
1044        for drs_box in &self.boxes {
1045            for referent in &drs_box.universe {
1046                if referent.variable == var {
1047                    return true;
1048                }
1049            }
1050        }
1051        false
1052    }
1053
1054    /// Resolve bridging anaphora by finding referents whose type contains the noun as a part.
1055    /// Returns matching referent and whole name for PartOf relation.
1056    pub fn resolve_bridging(
1057        &self,
1058        interner: &crate::Interner,
1059        noun_class: Symbol,
1060    ) -> Option<(Symbol, &'static str)> {
1061        use crate::ontology::find_bridging_wholes;
1062
1063        let noun_str = interner.resolve(noun_class);
1064        let Some(wholes) = find_bridging_wholes(noun_str) else {
1065            return None;
1066        };
1067
1068        // Look for a referent whose noun_class matches one of the possible wholes
1069        for whole in wholes {
1070            for drs_box in &self.boxes {
1071                for referent in drs_box.universe.iter().rev() {
1072                    let ref_class_str = interner.resolve(referent.noun_class);
1073                    if ref_class_str.eq_ignore_ascii_case(whole) {
1074                        return Some((referent.variable, *whole));
1075                    }
1076                }
1077            }
1078        }
1079        None
1080    }
1081
1082    /// Get all referents that should receive universal quantification
1083    pub fn get_universal_referents(&self) -> Vec<Symbol> {
1084        let mut result = Vec::new();
1085        for drs_box in &self.boxes {
1086            for referent in &drs_box.universe {
1087                // Proper names are rigid constants, never universally bound — a
1088                // counterfactual "If John had studied…" must not become ∀John. Nor are
1089                // events: the transpiler binds every event of a conditional, and a second
1090                // binder here would bind it twice.
1091                if referent.should_be_universal()
1092                    && !matches!(referent.source, ReferentSource::ProperName)
1093                    && !referent.is_event
1094                {
1095                    result.push(referent.variable);
1096                }
1097            }
1098        }
1099        result
1100    }
1101
1102    /// Get all referents that should receive existential quantification
1103    pub fn get_existential_referents(&self) -> Vec<Symbol> {
1104        let mut result = Vec::new();
1105        for drs_box in &self.boxes {
1106            for referent in &drs_box.universe {
1107                if !referent.should_be_universal()
1108                    && !matches!(referent.source, ReferentSource::ProperName)
1109                {
1110                    result.push(referent.variable);
1111                }
1112            }
1113        }
1114        result
1115    }
1116
1117    /// Get the most recent event referent (for binding weather adjectives to events)
1118    pub fn get_last_event_referent(&self, interner: &crate::intern::Interner) -> Option<Symbol> {
1119        // Search all boxes in reverse order for event referents
1120        for drs_box in self.boxes.iter().rev() {
1121            for referent in drs_box.universe.iter().rev() {
1122                let class_str = interner.resolve(referent.noun_class);
1123                if class_str == "Event" {
1124                    return Some(referent.variable);
1125                }
1126            }
1127        }
1128        None
1129    }
1130
1131    /// Check if we're currently in a conditional antecedent
1132    pub fn in_conditional_antecedent(&self) -> bool {
1133        matches!(
1134            self.boxes.get(self.current_box).and_then(|b| b.box_type),
1135            Some(BoxType::ConditionalAntecedent)
1136        )
1137    }
1138
1139    /// Check if we're currently in a universal restrictor
1140    pub fn in_universal_restrictor(&self) -> bool {
1141        matches!(
1142            self.boxes.get(self.current_box).and_then(|b| b.box_type),
1143            Some(BoxType::UniversalRestrictor)
1144        )
1145    }
1146
1147    /// Get all referents that can telescope across sentence boundaries.
1148    /// Only includes referents from boxes where can_telescope() is true.
1149    /// Excludes referents blocked by negation or disjunction.
1150    pub fn get_telescope_candidates(&self) -> Vec<TelescopeCandidate> {
1151        let mut candidates = Vec::new();
1152
1153        for (box_idx, drs_box) in self.boxes.iter().enumerate() {
1154            // Check if this box type allows telescoping
1155            if let Some(box_type) = drs_box.box_type {
1156                if !box_type.can_telescope() {
1157                    continue; // Skip negation and disjunction boxes
1158                }
1159            }
1160
1161            // Check if this box is blocked by an ancestor negation/disjunction
1162            let mut is_blocked = false;
1163            let mut check_idx = box_idx;
1164            while let Some(parent_idx) = self.boxes.get(check_idx).and_then(|b| b.parent) {
1165                if let Some(parent_type) = self.boxes.get(parent_idx).and_then(|b| b.box_type) {
1166                    if parent_type.blocks_accessibility() {
1167                        is_blocked = true;
1168                        break;
1169                    }
1170                }
1171                check_idx = parent_idx;
1172            }
1173
1174            if is_blocked {
1175                continue;
1176            }
1177
1178            // Collect referents from this box (skip those with blocking sources)
1179            let is_modal_box = drs_box.box_type == Some(BoxType::ModalScope);
1180            for referent in &drs_box.universe {
1181                // Skip referents that are marked with NegationScope or Disjunct source
1182                // These are trapped inside negation/disjunction and cannot telescope
1183                if matches!(
1184                    referent.source,
1185                    ReferentSource::NegationScope | ReferentSource::Disjunct
1186                ) {
1187                    continue;
1188                }
1189
1190                candidates.push(TelescopeCandidate {
1191                    variable: referent.variable,
1192                    noun_class: referent.noun_class,
1193                    gender: referent.gender,
1194                    origin_box: box_idx,
1195                    scope_path: Vec::new(), // TODO: Track scope path during parsing
1196                    in_modal_scope: is_modal_box || referent.source == ReferentSource::ModalScope,
1197                });
1198            }
1199        }
1200
1201        candidates
1202    }
1203
1204    /// Find a referent that matches but is blocked by scope.
1205    /// Used to generate informative error messages.
1206    pub fn find_blocked_referent(
1207        &self,
1208        from_box: usize,
1209        gender: Gender,
1210    ) -> Option<(Symbol, BoxType)> {
1211        for (box_idx, drs_box) in self.boxes.iter().enumerate() {
1212            // Only check boxes that are NOT accessible
1213            if self.is_accessible(box_idx, from_box) {
1214                continue;
1215            }
1216
1217            // Check if this box type blocks access
1218            if let Some(box_type) = drs_box.box_type {
1219                if box_type.blocks_accessibility() {
1220                    for referent in &drs_box.universe {
1221                        let gender_match = gender == Gender::Unknown
1222                            || referent.gender == Gender::Unknown
1223                            || referent.gender == gender
1224                            || gender == Gender::Neuter;
1225
1226                        if gender_match {
1227                            return Some((referent.variable, box_type));
1228                        }
1229                    }
1230                }
1231            }
1232        }
1233        None
1234    }
1235
1236    /// Set ownership state for a referent by noun class
1237    pub fn set_ownership(&mut self, noun_class: Symbol, state: OwnershipState) {
1238        for drs_box in &mut self.boxes {
1239            for referent in &mut drs_box.universe {
1240                if referent.noun_class == noun_class {
1241                    referent.ownership = state;
1242                    return;
1243                }
1244            }
1245        }
1246    }
1247
1248    /// Set ownership state for a referent by variable name
1249    pub fn set_ownership_by_var(&mut self, var: Symbol, state: OwnershipState) {
1250        for drs_box in &mut self.boxes {
1251            for referent in &mut drs_box.universe {
1252                if referent.variable == var {
1253                    referent.ownership = state;
1254                    return;
1255                }
1256            }
1257        }
1258    }
1259
1260    /// Get ownership state for a referent by noun class
1261    pub fn get_ownership(&self, noun_class: Symbol) -> Option<OwnershipState> {
1262        for drs_box in &self.boxes {
1263            for referent in &drs_box.universe {
1264                if referent.noun_class == noun_class {
1265                    return Some(referent.ownership);
1266                }
1267            }
1268        }
1269        None
1270    }
1271
1272    /// Get ownership state for a referent by variable name
1273    pub fn get_ownership_by_var(&self, var: Symbol) -> Option<OwnershipState> {
1274        for drs_box in &self.boxes {
1275            for referent in &drs_box.universe {
1276                if referent.variable == var {
1277                    return Some(referent.ownership);
1278                }
1279            }
1280        }
1281        None
1282    }
1283
1284    pub fn clear(&mut self) {
1285        self.boxes.clear();
1286        let main = DrsBox::new(BoxType::Main, None);
1287        self.boxes.push(main);
1288        self.main_box = 0;
1289        self.current_box = 0;
1290        self.item_categories.clear();
1291    }
1292}
1293
1294impl Default for Drs {
1295    fn default() -> Self {
1296        Self::new()
1297    }
1298}
1299
1300#[cfg(test)]
1301#[path = "../../logicaffeine_tests/unit/logicaffeine_language/drs/tests.rs"]
1302mod tests;