Skip to main content

logicaffeine_language/parser/
question.rs

1//! Question parsing: wh-questions and yes/no questions.
2//!
3//! This module handles interrogative sentences including:
4//!
5//! - **Wh-questions**: "Who runs?", "What does John love?", "Where did Mary go?"
6//! - **Yes/no questions**: "Does John run?", "Is Mary tall?"
7//! - **Pied-piping**: "To whom did John give the book?"
8//!
9//! # Wh-Movement
10//!
11//! Wh-words introduce a question variable that is moved to sentence-initial
12//! position. The parser tracks the "gap" (extraction site) using the filler-gap
13//! dependency mechanism.
14//!
15//! Questions are represented using `LogicExpr::Question` with a `wh_variable`
16//! binding the questioned entity.
17
18use super::noun::NounParsing;
19use super::quantifier::QuantifierParsing;
20use super::verb::LogicVerbParsing;
21use super::{ParseResult, Parser};
22use crate::ast::{AspectOperator, LogicExpr, ModalDomain, ModalVector, TemporalOperator, Term};
23use crate::lexicon::{Aspect, Time};
24use crate::token::TokenType;
25
26/// Trait for parsing interrogative sentences.
27///
28/// Provides methods for parsing wh-questions (who, what, where) and
29/// yes/no questions with subject-auxiliary inversion.
30pub trait QuestionParsing<'a, 'ctx, 'int> {
31    /// Parses a wh-question: "Who runs?", "What does John love?".
32    fn parse_wh_question(&mut self) -> ParseResult<&'a LogicExpr<'a>>;
33    /// Parses a yes/no question: "Does John run?", "Is Mary tall?".
34    fn parse_yes_no_question(&mut self) -> ParseResult<&'a LogicExpr<'a>>;
35    /// Converts an auxiliary token to its modal vector for questions.
36    fn aux_token_to_modal_vector(&self, token: &TokenType) -> ModalVector;
37}
38
39impl<'a, 'ctx, 'int> QuestionParsing<'a, 'ctx, 'int> for Parser<'a, 'ctx, 'int> {
40    fn parse_wh_question(&mut self) -> ParseResult<&'a LogicExpr<'a>> {
41        let pied_piping_prep = if self.check_preposition() {
42            let prep = self.advance().kind.clone();
43            Some(prep)
44        } else {
45            None
46        };
47
48        let wh_token = self.advance().kind.clone();
49        let var_name = self.interner.intern("x");
50        let var_term = Term::Variable(var_name);
51
52        if pied_piping_prep.is_some() && self.check_auxiliary() {
53            let aux_token = self.advance().clone();
54            if let TokenType::Auxiliary(time) = aux_token.kind {
55                self.pending_time = Some(time);
56            }
57
58            let subject = self.parse_noun_phrase(true)?;
59            let verb = self.consume_verb();
60
61            let mut args = vec![Term::Constant(subject.noun)];
62            if self.check_content_word() || self.check_article() {
63                let object = self.parse_noun_phrase(false)?;
64                args.push(Term::Constant(object.noun));
65            }
66            args.push(var_term);
67
68            let body = self.ctx.exprs.alloc(LogicExpr::Predicate {
69                name: verb,
70                args: self.ctx.terms.alloc_slice(args),
71                world: None,
72            });
73            return Ok(self.ctx.exprs.alloc(LogicExpr::Question {
74                wh_variable: var_name,
75                body,
76            }));
77        }
78
79        // "Who is a lawyer?" / "Who is the doctor?" / "Who is mortal?" — a COPULA
80        // wh-question. The complement (a nominal or an adjective) is predicated of
81        // the answer variable → Question{x, P(x)}; the wh-word IS the subject, so a
82        // bare predicate over `x` is exactly the goal whose witness is the answer.
83        if matches!(
84            self.peek().kind,
85            TokenType::Is | TokenType::Are | TokenType::Was | TokenType::Were
86        ) {
87            self.advance(); // copula
88                            // "Who is in Maine?" / "What is on the table?" — a PP complement →
89                            // Question{x, In(x, Maine)}: the answer is the entity standing in that
90                            // relation. The locative question a logic grid asks ("who is in <state>",
91                            // "who is in <year>").
92            if self.check_preposition() && !self.check_by_preposition() {
93                let prep_sym = match self.advance().kind {
94                    TokenType::Preposition(s) => s,
95                    _ => unreachable!("guarded by check_preposition"),
96                };
97                let obj = self.parse_noun_phrase(false)?;
98                let body = self.ctx.exprs.alloc(LogicExpr::Predicate {
99                    name: prep_sym,
100                    args: self
101                        .ctx
102                        .terms
103                        .alloc_slice([var_term, Term::Constant(obj.noun)]),
104                    world: None,
105                });
106                return Ok(self.ctx.exprs.alloc(LogicExpr::Question {
107                    wh_variable: var_name,
108                    body,
109                }));
110            }
111            if matches!(self.peek().kind, TokenType::Article(_)) {
112                self.advance(); // optional determiner ("a", "an", "the")
113            }
114            let pred = self.consume_content_word()?;
115            let body = self.ctx.exprs.alloc(LogicExpr::Predicate {
116                name: pred,
117                args: self.ctx.terms.alloc_slice([var_term]),
118                world: None,
119            });
120            return Ok(self.ctx.exprs.alloc(LogicExpr::Question {
121                wh_variable: var_name,
122                body,
123            }));
124        }
125
126        if self.check_verb() {
127            let verb = self.consume_verb();
128            let mut args = vec![var_term];
129
130            if self.check_content_word() {
131                let object = self.parse_noun_phrase(false)?;
132                args.push(Term::Constant(object.noun));
133            }
134
135            let body = self.ctx.exprs.alloc(LogicExpr::Predicate {
136                name: verb,
137                args: self.ctx.terms.alloc_slice(args),
138                world: None,
139            });
140            return Ok(self.ctx.exprs.alloc(LogicExpr::Question {
141                wh_variable: var_name,
142                body,
143            }));
144        }
145
146        if self.check(&TokenType::Does) || self.check(&TokenType::Do) {
147            self.advance();
148            let subject = self.parse_noun_phrase(true)?;
149            let verb = self.consume_verb();
150
151            let body = self.ctx.exprs.alloc(LogicExpr::Predicate {
152                name: verb,
153                args: self
154                    .ctx
155                    .terms
156                    .alloc_slice([Term::Constant(subject.noun), var_term]),
157                world: None,
158            });
159            return Ok(self.ctx.exprs.alloc(LogicExpr::Question {
160                wh_variable: var_name,
161                body,
162            }));
163        }
164
165        if self.check_auxiliary() {
166            let aux_token = self.advance().clone();
167            if let TokenType::Auxiliary(time) = aux_token.kind {
168                self.pending_time = Some(time);
169            }
170
171            self.filler_gap = Some(var_name);
172
173            let subject = self.parse_noun_phrase(true)?;
174            let body = self.parse_predicate_with_subject(subject.noun)?;
175
176            self.filler_gap = None;
177
178            return Ok(self.ctx.exprs.alloc(LogicExpr::Question {
179                wh_variable: var_name,
180                body,
181            }));
182        }
183
184        let unknown = self.interner.intern(&format!("{:?}", wh_token));
185        Ok(self.ctx.exprs.alloc(LogicExpr::Atom(unknown)))
186    }
187
188    fn parse_yes_no_question(&mut self) -> ParseResult<&'a LogicExpr<'a>> {
189        let aux_token = self.advance().kind.clone();
190
191        let is_modal = matches!(
192            aux_token,
193            TokenType::Can
194                | TokenType::Could
195                | TokenType::Would
196                | TokenType::May
197                | TokenType::Must
198                | TokenType::Should
199        );
200        let is_copula = matches!(
201            aux_token,
202            TokenType::Is | TokenType::Are | TokenType::Was | TokenType::Were
203        );
204        let copula_time = if matches!(aux_token, TokenType::Was | TokenType::Were) {
205            Time::Past
206        } else {
207            Time::Present
208        };
209
210        if self.check_quantifier() {
211            self.advance();
212            let quantified = self.parse_quantified()?;
213            let wrapped = if is_modal {
214                let vector = self.aux_token_to_modal_vector(&aux_token);
215                self.ctx.exprs.alloc(LogicExpr::Modal {
216                    vector,
217                    operand: quantified,
218                })
219            } else {
220                quantified
221            };
222            return Ok(self
223                .ctx
224                .exprs
225                .alloc(LogicExpr::YesNoQuestion { body: wrapped }));
226        }
227
228        let subject_symbol = if self.check_pronoun() {
229            let token = self.advance().clone();
230            if let TokenType::Pronoun { gender, number, .. } = token.kind {
231                let token_text = self.interner.resolve(token.lexeme);
232                if token_text.eq_ignore_ascii_case("you") {
233                    self.interner.intern("Addressee")
234                } else {
235                    let resolved = self.resolve_pronoun(gender, number)?;
236                    match resolved {
237                        super::ResolvedPronoun::Variable(s)
238                        | super::ResolvedPronoun::Constant(s) => s,
239                    }
240                }
241            } else {
242                self.interner.intern("?")
243            }
244        } else {
245            self.parse_noun_phrase(true)?.noun
246        };
247
248        let please_sym = self.interner.intern("please");
249        self.match_token(&[TokenType::Adverb(please_sym)]);
250
251        if is_copula {
252            let body = if self.check_verb() {
253                let (verb, _, verb_aspect, _) = self.consume_verb_with_metadata();
254                let predicate = self.ctx.exprs.alloc(LogicExpr::Predicate {
255                    name: verb,
256                    args: self.ctx.terms.alloc_slice([Term::Constant(subject_symbol)]),
257                    world: None,
258                });
259                let with_aspect = if verb_aspect == Aspect::Progressive {
260                    self.ctx.exprs.alloc(LogicExpr::Aspectual {
261                        operator: AspectOperator::Progressive,
262                        body: predicate,
263                    })
264                } else {
265                    predicate
266                };
267                if copula_time == Time::Past {
268                    self.ctx.exprs.alloc(LogicExpr::Temporal {
269                        operator: TemporalOperator::Past,
270                        body: with_aspect,
271                    })
272                } else {
273                    with_aspect
274                }
275            } else if self.check_content_word() {
276                let adj = self.consume_content_word()?;
277                self.ctx.exprs.alloc(LogicExpr::Predicate {
278                    name: adj,
279                    args: self.ctx.terms.alloc_slice([Term::Constant(subject_symbol)]),
280                    world: None,
281                })
282            } else {
283                self.ctx.exprs.alloc(LogicExpr::Atom(subject_symbol))
284            };
285            return Ok(self.ctx.exprs.alloc(LogicExpr::YesNoQuestion { body }));
286        }
287
288        let body = self.parse_predicate_with_subject(subject_symbol)?;
289
290        let wrapped_body = if is_modal {
291            let vector = self.aux_token_to_modal_vector(&aux_token);
292            self.ctx.exprs.alloc(LogicExpr::Modal {
293                vector,
294                operand: body,
295            })
296        } else {
297            body
298        };
299
300        Ok(self
301            .ctx
302            .exprs
303            .alloc(LogicExpr::YesNoQuestion { body: wrapped_body }))
304    }
305
306    fn aux_token_to_modal_vector(&self, token: &TokenType) -> ModalVector {
307        use crate::ast::ModalFlavor;
308        match token {
309            // Root modals (narrow scope)
310            TokenType::Can => ModalVector {
311                domain: ModalDomain::Alethic,
312                force: 0.5,
313                flavor: ModalFlavor::Root,
314                modal_base: None,
315                ordering_source: None,
316            },
317            TokenType::Could => ModalVector {
318                domain: ModalDomain::Alethic,
319                force: 0.4,
320                flavor: ModalFlavor::Root,
321                modal_base: None,
322                ordering_source: None,
323            },
324            TokenType::Would => ModalVector {
325                domain: ModalDomain::Alethic,
326                force: 0.6,
327                flavor: ModalFlavor::Root,
328                modal_base: None,
329                ordering_source: None,
330            },
331            TokenType::Must => ModalVector {
332                domain: ModalDomain::Alethic,
333                force: 1.0,
334                flavor: ModalFlavor::Root,
335                modal_base: None,
336                ordering_source: None,
337            },
338            TokenType::Should => ModalVector {
339                domain: ModalDomain::Deontic,
340                force: 0.6,
341                flavor: ModalFlavor::Root,
342                modal_base: None,
343                ordering_source: None,
344            },
345            // Epistemic modals (wide scope)
346            TokenType::May => ModalVector {
347                domain: ModalDomain::Deontic,
348                force: 0.5,
349                flavor: ModalFlavor::Epistemic,
350                modal_base: None,
351                ordering_source: None,
352            },
353            TokenType::Might => ModalVector {
354                domain: ModalDomain::Alethic,
355                force: 0.3,
356                flavor: ModalFlavor::Epistemic,
357                modal_base: None,
358                ordering_source: None,
359            },
360            _ => ModalVector {
361                domain: ModalDomain::Alethic,
362                force: 0.5,
363                flavor: ModalFlavor::Root,
364                modal_base: None,
365                ordering_source: None,
366            },
367        }
368    }
369}