Skip to main content

logicaffeine_language/parser/
modal.rs

1//! Modal verb parsing with Kripke semantics support.
2//!
3//! This module handles modal auxiliaries (can, could, may, might, must, should, would)
4//! and their semantic interpretation using modal vectors that encode:
5//!
6//! - **Domain**: Alethic (possibility/necessity) vs Deontic (permission/obligation)
7//! - **Flavor**: Root (circumstantial) vs Epistemic (knowledge-based)
8//! - **Force**: Possibility (◇) vs Necessity (□)
9//!
10//! # Modal Vector Examples
11//!
12//! | Modal | Default Reading | Alternative Reading |
13//! |-------|-----------------|---------------------|
14//! | can   | Ability (Root)  | Permission (Deontic) |
15//! | may   | Permission (Deontic) | Possibility (Epistemic) |
16//! | must  | Necessity (Root) | Obligation (Deontic) |
17//! | might | Possibility (Epistemic) | - |
18//!
19//! The module also handles aspect chains (perfect "have", progressive "be -ing").
20
21use super::clause::ClauseParsing;
22use super::noun::NounParsing;
23use super::pragmatics::PragmaticsParsing;
24use super::quantifier::QuantifierParsing;
25use super::{ParseResult, Parser};
26use crate::ast::{
27    AspectOperator, LogicExpr, ModalDomain, ModalFlavor, ModalVector, NeoEventData, QuantifierKind,
28    Term, ThematicRole, VoiceOperator,
29};
30use crate::drs::TimeRelation;
31use crate::error::{ParseError, ParseErrorKind};
32use crate::lexicon::{Aspect, Time};
33use crate::token::TokenType;
34use logicaffeine_base::Symbol;
35
36/// Trait for parsing modal verbs and aspect chains.
37///
38/// Provides methods for interpreting modal auxiliaries (can, must, etc.)
39/// with Kripke semantics and handling aspect markers (perfect, progressive).
40pub trait ModalParsing<'a, 'ctx, 'int> {
41    /// Parses a modal verb and its scope content.
42    fn parse_modal(&mut self) -> ParseResult<&'a LogicExpr<'a>>;
43    /// Parses perfect/progressive aspect chain with a symbol subject.
44    fn parse_aspect_chain(&mut self, subject_symbol: Symbol) -> ParseResult<&'a LogicExpr<'a>>;
45    /// Parses perfect/progressive aspect chain with a term subject.
46    fn parse_aspect_chain_with_term(
47        &mut self,
48        subject_term: Term<'a>,
49    ) -> ParseResult<&'a LogicExpr<'a>>;
50    /// Converts a modal token to its semantic vector (domain, force, flavor).
51    fn token_to_vector(&self, token: &TokenType) -> ModalVector;
52}
53
54impl<'a, 'ctx, 'int> ModalParsing<'a, 'ctx, 'int> for Parser<'a, 'ctx, 'int> {
55    fn parse_modal(&mut self) -> ParseResult<&'a LogicExpr<'a>> {
56        use crate::drs::BoxType;
57
58        let vector = self.token_to_vector(&self.previous().kind.clone());
59
60        // Enter modal box in parser's DRS (not world_state - that's swapped at sentence boundaries)
61        self.drs.enter_box(BoxType::ModalScope);
62
63        if self.check(&TokenType::That) {
64            self.advance();
65        }
66
67        let content = self.parse_sentence()?;
68
69        // Exit modal box
70        self.drs.exit_box();
71
72        Ok(self.ctx.exprs.alloc(LogicExpr::Modal {
73            vector,
74            operand: content,
75        }))
76    }
77
78    fn parse_aspect_chain(&mut self, subject_symbol: Symbol) -> ParseResult<&'a LogicExpr<'a>> {
79        self.parse_aspect_chain_with_term(Term::Constant(subject_symbol))
80    }
81
82    fn parse_aspect_chain_with_term(
83        &mut self,
84        subject_term: Term<'a>,
85    ) -> ParseResult<&'a LogicExpr<'a>> {
86        let mut has_modal = false;
87        let mut modal_vector = None;
88        let mut has_negation = false;
89        let mut has_perfect = false;
90        let mut has_passive = false;
91        let mut has_progressive = false;
92
93        if self.check(&TokenType::Would)
94            || self.check(&TokenType::Could)
95            || self.check(&TokenType::Must)
96            || self.check(&TokenType::Can)
97            || self.check(&TokenType::Should)
98            || self.check(&TokenType::May)
99            || self.check(&TokenType::Cannot)
100            || self.check(&TokenType::Might)
101            || self.check(&TokenType::Shall)
102        {
103            let modal_token = self.peek().kind.clone();
104            self.advance();
105            has_modal = true;
106            let vector = self.token_to_vector(&modal_token);
107            modal_vector = Some(vector.clone());
108            // Enter modal box in DRS so any new referents are marked as hypothetical
109            // This ensures "A wolf might enter" puts the wolf in a modal scope
110            self.drs.enter_box(crate::drs::BoxType::ModalScope);
111            // Also set modal context on WorldState for cross-sentence tracking
112            // This is used by end_sentence() to mark telescope candidates as modal-sourced
113            let is_epistemic = matches!(vector.flavor, crate::ast::ModalFlavor::Epistemic);
114            self.world_state
115                .enter_modal_context(is_epistemic, vector.force);
116        }
117
118        if self.check(&TokenType::Not) {
119            self.advance();
120            has_negation = true;
121        }
122
123        // "shall never send" / "must never fail" — treat Never as negation
124        if self.check(&TokenType::Never) && !has_negation {
125            self.advance();
126            has_negation = true;
127        }
128
129        // Check for "be able to" periphrastic modal (= can)
130        // This creates a nested modal: "might be able to fly" → ◇◇Fly(x)
131        let mut nested_modal_vector = None;
132        if self.check_content_word() {
133            let word = self.interner.resolve(self.peek().lexeme).to_lowercase();
134            if word == "be" {
135                // Look ahead for "able to"
136                if let Some(next1) = self.tokens.get(self.current + 1) {
137                    let next1_word = self.interner.resolve(next1.lexeme).to_lowercase();
138                    if next1_word == "able" {
139                        if let Some(next2) = self.tokens.get(self.current + 2) {
140                            if matches!(next2.kind, TokenType::To) {
141                                // Consume "be able to" - it's a modal meaning "can" (ability)
142                                self.advance(); // consume "be"
143                                self.advance(); // consume "able"
144                                self.advance(); // consume "to"
145                                nested_modal_vector = Some(ModalVector {
146                                    domain: ModalDomain::Alethic,
147                                    force: 0.5,                // ability = possibility
148                                    flavor: ModalFlavor::Root, // "be able to" = Root modal (ability)
149                                    modal_base: None,
150                                    ordering_source: None,
151                                });
152                            }
153                        }
154                    }
155                }
156            }
157        }
158
159        if self.check_content_word() {
160            let word = self.interner.resolve(self.peek().lexeme).to_lowercase();
161            if word == "have" || word == "has" || word == "had" {
162                self.advance();
163                has_perfect = true;
164            }
165        }
166
167        if self.check(&TokenType::Had) {
168            self.advance();
169            has_perfect = true;
170            // "had" = past perfect: R < S (past reference time)
171            let r_var = self.world_state.next_reference_time();
172            self.world_state
173                .add_time_constraint(r_var, TimeRelation::Precedes, "S".to_string());
174        }
175
176        if self.check_content_word() {
177            let word = self.interner.resolve(self.peek().lexeme).to_lowercase();
178            if word == "been" {
179                self.advance();
180
181                if self.check_verb() {
182                    match &self.peek().kind {
183                        TokenType::Verb {
184                            aspect: Aspect::Progressive,
185                            ..
186                        } => {
187                            has_progressive = true;
188                        }
189                        TokenType::Verb { .. } => {
190                            let next_word = self.interner.resolve(self.peek().lexeme);
191                            if next_word.ends_with("ing") {
192                                has_progressive = true;
193                            } else {
194                                has_passive = true;
195                            }
196                        }
197                        _ => {
198                            has_passive = true;
199                        }
200                    }
201                }
202            }
203        }
204
205        if self.check_content_word() {
206            let word = self.interner.resolve(self.peek().lexeme).to_lowercase();
207            if word == "being" {
208                self.advance();
209                has_progressive = true;
210            }
211        }
212
213        // Presupposition trigger under the modal/aspect chain: "Mary might
214        // regret lying." The presupposition PROJECTS out of the modal (Van
215        // der Sandt global accommodation) — the modal wraps only the
216        // assertion: Presup(◇Regret(m), ⟨Lied(m)⟩).
217        if self.check_presup_trigger()
218            && !self.is_followed_by_np_object()
219            && self.is_followed_by_gerund()
220        {
221            if let Term::Constant(subj_sym) = subject_term {
222                let presup_kind = match self.advance().kind {
223                    TokenType::PresupTrigger(kind) => kind,
224                    TokenType::Verb { lemma, .. } => {
225                        let s = self.interner.resolve(lemma).to_lowercase();
226                        crate::lexicon::lookup_presup_trigger(&s)
227                            .expect("Lexicon mismatch: Verb flagged as trigger but lookup failed")
228                    }
229                    _ => unreachable!("guarded by check_presup_trigger"),
230                };
231                let subject_np = crate::ast::NounPhrase::simple(subj_sym);
232                let parsed = self.parse_presupposition(&subject_np, presup_kind, has_negation)?;
233                if has_modal {
234                    self.drs.exit_box();
235                }
236                if let LogicExpr::Presupposition {
237                    assertion,
238                    presupposition,
239                } = parsed
240                {
241                    let mut asserted: &'a LogicExpr<'a> = assertion;
242                    if has_modal {
243                        if let Some(vector) = modal_vector {
244                            asserted = self.ctx.modal(vector, asserted);
245                        }
246                    }
247                    return Ok(self.ctx.exprs.alloc(LogicExpr::Presupposition {
248                        assertion: asserted,
249                        presupposition,
250                    }));
251                }
252                let mut result: &'a LogicExpr<'a> = parsed;
253                if has_modal {
254                    if let Some(vector) = modal_vector {
255                        result = self.ctx.modal(vector, result);
256                    }
257                }
258                return Ok(result);
259            }
260        }
261
262        let verb = if self.check_verb() {
263            self.consume_verb()
264        } else if self.check_content_word() {
265            self.consume_content_word()?
266        } else {
267            return Err(ParseError {
268                kind: ParseErrorKind::ExpectedContentWord {
269                    found: self.peek().kind.clone(),
270                },
271                span: self.peek().span.clone(),
272            });
273        };
274
275        let subject_role = if has_passive {
276            ThematicRole::Theme
277        } else {
278            ThematicRole::Agent
279        };
280        let mut roles: Vec<(ThematicRole, Term<'a>)> = vec![(subject_role, subject_term)];
281        let mut object_quant: Option<(TokenType, Symbol, &'a LogicExpr<'a>)> = None;
282        // A DESCRIPTIVE perfect-passive by-agent ("…has been caught by the local
283        // police") becomes its own restrictor-carrying entity scoping the whole
284        // event; captured here, the wrap is applied to the finished `result` below
285        // so the Agent variable it binds stays in scope. Bare agents → None.
286        let mut agent_restr: Option<(Symbol, &'a LogicExpr<'a>)> = None;
287
288        if has_passive && self.check_preposition() {
289            if let TokenType::Preposition(sym) = self.peek().kind {
290                if self.interner.resolve(sym) == "by" {
291                    self.advance();
292                    let agent_np = self.parse_noun_phrase(true)?;
293                    let (agent_term, restr) = self.possessor_entity(&agent_np);
294                    agent_restr = restr;
295                    roles.push((ThematicRole::Agent, agent_term));
296                }
297            }
298        } else if !has_passive && self.counting_np_lookahead().is_some() {
299            // A counting-NP object under a perfect/modal ("has done 49 previous
300            // jumps"): a ∃=n entity that is the Theme, keeping the count AND the
301            // adjectives (the noun-only object_quant path below drops them).
302            let n = self.counting_np_lookahead().unwrap();
303            self.advance(); // the number
304            let var = self.next_var_name();
305            self.nominal_np_context = true;
306            let obj_np_result = self.parse_noun_phrase(false);
307            self.nominal_np_context = false;
308            let obj_np = obj_np_result?;
309            let mut restriction: &'a LogicExpr<'a> = self.ctx.exprs.alloc(LogicExpr::Predicate {
310                name: obj_np.noun,
311                args: self.ctx.terms.alloc_slice([Term::Variable(var)]),
312                world: None,
313            });
314            for &adj in obj_np.adjectives {
315                let adj_pred = self.adjective_restriction(adj, var, obj_np.noun);
316                restriction = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
317                    left: restriction,
318                    op: TokenType::And,
319                    right: adj_pred,
320                });
321            }
322            for pp in obj_np.pps {
323                let pp_sub = self.substitute_pp_placeholder(pp, var);
324                restriction = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
325                    left: restriction,
326                    op: TokenType::And,
327                    right: pp_sub,
328                });
329            }
330            roles.push((ThematicRole::Theme, Term::Variable(var)));
331            object_quant = Some((TokenType::Cardinal(n), var, restriction));
332        } else if !has_passive && QuantifierKind::of_determiner(&self.peek().kind).is_some() {
333            // Quantified object under a modal ("shall acknowledge every
334            // request", "shall never drop two consecutive bytes"): the
335            // object raises past the root modal —
336            // ∀x(Request(x) → MODAL(event with Theme x)).
337            let determiner = self.advance().kind.clone();
338            let obj_np = self.parse_noun_phrase(false)?;
339            let var = self.next_var_name();
340            roles.push((ThematicRole::Theme, Term::Variable(var)));
341            let restriction = self.ctx.exprs.alloc(LogicExpr::Predicate {
342                name: obj_np.noun,
343                args: self.ctx.terms.alloc_slice([Term::Variable(var)]),
344                world: None,
345            });
346            object_quant = Some((determiner, var, restriction));
347        } else if !has_passive && (self.check_content_word() || self.check_article()) {
348            let obj_np = self.parse_noun_phrase(false)?;
349            let obj_term = self.noun_phrase_to_term(&obj_np);
350            roles.push((ThematicRole::Theme, obj_term));
351        } else if !has_passive && self.check_pronoun() {
352            // Pronoun object ("A wolf would eat you."): person deictics resolve
353            // to discourse roles, third person to the discourse referent.
354            let token = self.advance().clone();
355            let plex = self.interner.resolve(token.lexeme).to_lowercase();
356            let obj_term = match plex.as_str() {
357                "you" | "yourself" => Term::Constant(self.interner.intern("Addressee")),
358                "i" | "me" | "myself" => Term::Constant(self.interner.intern("Speaker")),
359                _ => {
360                    let (gender, number) = match &token.kind {
361                        TokenType::Pronoun { gender, number, .. } => (*gender, *number),
362                        _ => (crate::drs::Gender::Unknown, crate::drs::Number::Singular),
363                    };
364                    match self.resolve_pronoun(gender, number)? {
365                        super::ResolvedPronoun::Variable(s) => Term::Variable(s),
366                        super::ResolvedPronoun::Constant(s) => Term::Constant(s),
367                    }
368                }
369            };
370            roles.push((ThematicRole::Theme, obj_term));
371        }
372
373        let event_var = self.get_event_var();
374        let mut modifiers: Vec<Symbol> = Vec::new();
375        // Manner adverbs under the modal ("would spread quickly").
376        modifiers.extend(self.collect_adverbs());
377        if let Some(pending) = self.pending_time {
378            match pending {
379                Time::Past => modifiers.push(self.interner.intern("Past")),
380                Time::Future => modifiers.push(self.interner.intern("Future")),
381                _ => {}
382            }
383        }
384        let suppress_existential = self.drs.in_conditional_antecedent();
385        let base_pred = self
386            .ctx
387            .exprs
388            .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
389                event_var,
390                verb,
391                roles: self.ctx.roles.alloc_slice(roles.clone()),
392                modifiers: self.ctx.syms.alloc_slice(modifiers.clone()),
393                suppress_existential,
394                world: None,
395            })));
396
397        // PPs and clause-final particles under the modal ("might walk in",
398        // "would go to the store") modify the same event.
399        let mut base_pred: &'a LogicExpr<'a> = base_pred;
400        while self.check_preposition() {
401            let prep_name = if let TokenType::Preposition(sym) = self.peek().kind {
402                sym
403            } else {
404                break;
405            };
406            // A measure object ("can fly FOR 40 minutes", "runs at 5 mph") — the
407            // amount is the PP's object, kept so the duration/rate isn't dropped.
408            // "with 190 degree WATER" — a measure-premodified noun (head two
409            // tokens past the number, i.e. after the unit) is ONE folded entity,
410            // routed to the NP branch, not a bare measure with the head stranded.
411            let head_after_unit = matches!(
412                self.tokens.get(self.current + 3).map(|t| &t.kind),
413                Some(TokenType::Noun(_)) | Some(TokenType::Ambiguous { .. })
414            );
415            let measure_follows = matches!(
416                self.tokens.get(self.current + 1).map(|t| &t.kind),
417                Some(TokenType::Number(_) | TokenType::Cardinal(_))
418            ) && !head_after_unit;
419            let np_follows = head_after_unit
420                || match self.tokens.get(self.current + 1).map(|t| &t.kind) {
421                    Some(TokenType::Noun(_) | TokenType::ProperName(_) | TokenType::Article(_)) => {
422                        true
423                    }
424                    // A noun READING suffices ("during transfer" — "transfer"
425                    // lexes Ambiguous{Verb|Noun}); the NP parse commits it.
426                    Some(TokenType::Ambiguous {
427                        primary,
428                        alternatives,
429                    }) => {
430                        matches!(**primary, TokenType::Noun(_))
431                            || alternatives.iter().any(|t| matches!(t, TokenType::Noun(_)))
432                    }
433                    _ => false,
434                };
435            let pp_pred = if measure_follows {
436                self.advance(); // preposition
437                let measure = self.parse_measure_phrase()?;
438                self.ctx.exprs.alloc(LogicExpr::Predicate {
439                    name: prep_name,
440                    args: self
441                        .ctx
442                        .terms
443                        .alloc_slice([Term::Variable(event_var), *measure]),
444                    world: None,
445                })
446            } else if np_follows {
447                self.advance(); // preposition
448                let saved_ctx = self.nominal_np_context;
449                self.nominal_np_context = true;
450                let pp_np_result = self.parse_noun_phrase(false);
451                self.nominal_np_context = saved_ctx;
452                let pp_np = pp_np_result?;
453                let pred: &'a LogicExpr<'a> = self.ctx.exprs.alloc(LogicExpr::Predicate {
454                    name: prep_name,
455                    args: self
456                        .ctx
457                        .terms
458                        .alloc_slice([Term::Variable(event_var), Term::Constant(pp_np.noun)]),
459                    world: None,
460                });
461                // "be caught by the LOCAL police" → By(e, Police) ∧ Local(Police):
462                // the PP object's modifiers survive via the shared helper.
463                self.attach_pp_object_modifiers(pred, &pp_np)
464            } else {
465                self.advance(); // preposition
466                if !self.at_clause_boundary()
467                    || !crate::lexicon::is_particle(
468                        &self.interner.resolve(prep_name).to_lowercase(),
469                    )
470                {
471                    // Not a lexical particle at a clause end — hand it back.
472                    self.current -= 1;
473                    break;
474                }
475                // Intransitive particle/directional: event modifier.
476                self.ctx.exprs.alloc(LogicExpr::Predicate {
477                    name: prep_name,
478                    args: self.ctx.terms.alloc_slice([Term::Variable(event_var)]),
479                    world: None,
480                })
481            };
482            base_pred = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
483                left: base_pred,
484                op: TokenType::And,
485                right: pp_pred,
486            });
487        }
488
489        // Capture template for ellipsis reconstruction
490        self.capture_event_template(verb, &roles, &modifiers);
491
492        let mut result: &'a LogicExpr<'a> = base_pred;
493
494        if has_progressive {
495            result = self.ctx.aspectual(AspectOperator::Progressive, result);
496        }
497
498        if has_passive {
499            result = self.ctx.voice(VoiceOperator::Passive, result);
500        }
501
502        if has_perfect {
503            result = self.ctx.aspectual(AspectOperator::Perfect, result);
504
505            // Check pending_time to set up reference time for tense
506            if let Some(pending) = self.pending_time.take() {
507                match pending {
508                    Time::Future => {
509                        // Future perfect: S < R
510                        let r_var = self.world_state.next_reference_time();
511                        self.world_state.add_time_constraint(
512                            "S".to_string(),
513                            TimeRelation::Precedes,
514                            r_var,
515                        );
516                    }
517                    Time::Past => {
518                        // Past perfect fallback (if not already set by "had")
519                        if self.world_state.current_reference_time() == "S" {
520                            let r_var = self.world_state.next_reference_time();
521                            self.world_state.add_time_constraint(
522                                r_var,
523                                TimeRelation::Precedes,
524                                "S".to_string(),
525                            );
526                        }
527                    }
528                    _ => {}
529                }
530            }
531
532            // Perfect: E < R (event before reference)
533            let e_var = format!("e{}", self.world_state.event_history().len().max(1));
534            let r_var = self.world_state.current_reference_time();
535            self.world_state
536                .add_time_constraint(e_var, TimeRelation::Precedes, r_var);
537        }
538
539        if has_negation {
540            result = self.ctx.exprs.alloc(LogicExpr::UnaryOp {
541                op: TokenType::Not,
542                operand: result,
543            });
544        }
545
546        // Apply nested modal first (from "be able to" = ability)
547        if let Some(vector) = nested_modal_vector {
548            result = self.ctx.modal(vector, result);
549        }
550
551        // Then apply outer modal (e.g., "might")
552        if has_modal {
553            // Exit modal box in DRS (matches enter_box above)
554            self.drs.exit_box();
555            // Note: We do NOT exit_modal_context() here because we want the modal flag
556            // to persist until end_sentence() so telescope candidates are marked as modal.
557            // The modal context is cleared by end_sentence() → prior_modal_context.take()
558            if let Some(vector) = modal_vector {
559                result = self.ctx.modal(vector, result);
560            }
561        }
562
563        if let Some((determiner, var, restriction)) = object_quant {
564            result = self.quantify_argument(&determiner, var, restriction, result);
565        }
566
567        let result = self.wrap_in_possessor_entity(agent_restr, result);
568        Ok(result)
569    }
570
571    fn token_to_vector(&self, token: &TokenType) -> ModalVector {
572        use super::ModalPreference;
573        use crate::ast::ModalFlavor;
574
575        match token {
576            // Root modals → Narrow Scope (De Re)
577            // These attach the modal to the predicate inside the quantifier
578            TokenType::Must => ModalVector {
579                domain: ModalDomain::Alethic,
580                force: 1.0,
581                flavor: ModalFlavor::Root,
582                modal_base: None,
583                ordering_source: None,
584            },
585            TokenType::Cannot => ModalVector {
586                domain: ModalDomain::Alethic,
587                force: 0.0,
588                flavor: ModalFlavor::Root,
589                modal_base: None,
590                ordering_source: None,
591            },
592
593            // Polysemous modal: CAN
594            // Default: Ability (Alethic, Root/Narrow)
595            // Deontic: Permission (Deontic, Root/Narrow)
596            TokenType::Can => {
597                match self.modal_preference {
598                    ModalPreference::Deontic => {
599                        // Permission: "You can go" (Deontic, Narrow Scope)
600                        ModalVector {
601                            domain: ModalDomain::Deontic,
602                            force: 0.5,
603                            flavor: ModalFlavor::Root,
604                            modal_base: None,
605                            ordering_source: None,
606                        }
607                    }
608                    _ => {
609                        // Ability: "Birds can fly" (Alethic, Narrow Scope)
610                        ModalVector {
611                            domain: ModalDomain::Alethic,
612                            force: 0.5,
613                            flavor: ModalFlavor::Root,
614                            modal_base: None,
615                            ordering_source: None,
616                        }
617                    }
618                }
619            }
620
621            // Polysemous modal: COULD
622            // Default: Past Ability (Alethic, Root/Narrow)
623            // Epistemic: Conditional Possibility (Alethic, Epistemic/Wide)
624            TokenType::Could => {
625                match self.modal_preference {
626                    ModalPreference::Epistemic => {
627                        // Conditional Possibility: "It could rain" (Alethic, Wide Scope)
628                        ModalVector {
629                            domain: ModalDomain::Alethic,
630                            force: 0.5,
631                            flavor: ModalFlavor::Epistemic,
632                            modal_base: None,
633                            ordering_source: None,
634                        }
635                    }
636                    _ => {
637                        // Past Ability: "She could swim" (Alethic, Narrow Scope)
638                        ModalVector {
639                            domain: ModalDomain::Alethic,
640                            force: 0.5,
641                            flavor: ModalFlavor::Root,
642                            modal_base: None,
643                            ordering_source: None,
644                        }
645                    }
646                }
647            }
648
649            TokenType::Would => ModalVector {
650                domain: ModalDomain::Alethic,
651                force: 0.5,
652                flavor: ModalFlavor::Root,
653                modal_base: None,
654                ordering_source: None,
655            },
656            TokenType::Shall => ModalVector {
657                domain: ModalDomain::Deontic,
658                force: 0.9,
659                flavor: ModalFlavor::Root,
660                modal_base: None,
661                ordering_source: None,
662            },
663            TokenType::Should => ModalVector {
664                domain: ModalDomain::Deontic,
665                force: 0.6,
666                flavor: ModalFlavor::Root,
667                modal_base: None,
668                ordering_source: None,
669            },
670
671            // Epistemic modals → Wide Scope (De Dicto)
672            // These wrap the entire quantifier in the modal
673            TokenType::Might => ModalVector {
674                domain: ModalDomain::Alethic,
675                force: 0.3,
676                flavor: ModalFlavor::Epistemic,
677                modal_base: None,
678                ordering_source: None,
679            },
680
681            // Polysemous modal: MAY
682            // Default: Permission (Deontic, Root/Narrow)
683            // Epistemic: Possibility (Alethic, Epistemic/Wide)
684            TokenType::May => {
685                match self.modal_preference {
686                    ModalPreference::Epistemic => {
687                        // Possibility: "It may rain" (Alethic, Wide Scope)
688                        ModalVector {
689                            domain: ModalDomain::Alethic,
690                            force: 0.5,
691                            flavor: ModalFlavor::Epistemic,
692                            modal_base: None,
693                            ordering_source: None,
694                        }
695                    }
696                    _ => {
697                        // Permission: "Students may leave" (Deontic, Narrow Scope)
698                        ModalVector {
699                            domain: ModalDomain::Deontic,
700                            force: 0.5,
701                            flavor: ModalFlavor::Root,
702                            modal_base: None,
703                            ordering_source: None,
704                        }
705                    }
706                }
707            }
708
709            _ => panic!("Unknown modal token: {:?}", token),
710        }
711    }
712}