logicaffeine_language/ast/logic.rs
1//! Logic expression AST types for first-order logic with modal and event extensions.
2//!
3//! This module defines the core logical expression types including:
4//!
5//! - **[`LogicExpr`]**: The main expression enum with all logical constructs
6//! - **[`Term`]**: Terms (constants, variables, function applications)
7//! - **[`NounPhrase`]**: Parsed noun phrase structure
8//! - **Semantic types**: Montague-style type markers
9//! - **Event roles**: Neo-Davidsonian thematic roles (Agent, Theme, Goal, etc.)
10//! - **Modal vectors**: Kripke semantics parameters (domain, flavor, force)
11//! - **Temporal operators**: Past, future, perfect, progressive
12//!
13//! All types use arena allocation with the `'a` lifetime parameter.
14
15use crate::lexicon::Definiteness;
16use crate::token::TokenType;
17use logicaffeine_base::Arena;
18use logicaffeine_base::Symbol;
19
20// ═══════════════════════════════════════════════════════════════════
21// Semantic Types (Montague Grammar)
22// ═══════════════════════════════════════════════════════════════════
23
24/// Montague semantic types for compositional interpretation.
25///
26/// These types classify expressions according to their denotation in
27/// a model-theoretic semantics, following Montague's "Universal Grammar".
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum LogicalType {
30 /// Type `e`: Individuals (entities) like "John" or "the ball".
31 Entity,
32 /// Type `t`: Truth values (propositions) like "John runs".
33 TruthValue,
34 /// Type `<e,t>`: Properties (one-place predicates) like "is a unicorn".
35 Property,
36 /// Type `<<e,t>,t>`: Generalized quantifiers like "every man" or "a woman".
37 Quantifier,
38}
39
40// ═══════════════════════════════════════════════════════════════════
41// Degree Semantics (Prover-Ready Number System)
42// ═══════════════════════════════════════════════════════════════════
43
44/// Physical dimension for degree semantics and unit tracking.
45///
46/// Used with [`NumberKind`] to enable dimensional analysis and prevent
47/// nonsensical comparisons (e.g., adding meters to seconds).
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub enum Dimension {
50 /// Spatial extent (meters, feet, inches).
51 Length,
52 /// Temporal duration (seconds, minutes, hours).
53 Time,
54 /// Mass (kilograms, pounds).
55 Weight,
56 /// Thermal measure (Celsius, Fahrenheit, Kelvin).
57 Temperature,
58 /// Count of discrete items.
59 Cardinality,
60}
61
62/// Numeric literal representation for degree semantics.
63///
64/// Supports exact integers, floating-point reals, and symbolic constants
65/// (e.g., π, e) for prover integration.
66#[derive(Debug, Clone, Copy, PartialEq)]
67pub enum NumberKind {
68 /// Floating-point real number (e.g., 3.14, 0.5).
69 Real(f64),
70 /// Exact integer (e.g., 42, -1, 0).
71 Integer(i64),
72 /// Symbolic constant (e.g., π, e, ∞).
73 Symbolic(Symbol),
74}
75
76// ═══════════════════════════════════════════════════════════════════
77// First-Order Logic Types (FOL Upgrade)
78// ═══════════════════════════════════════════════════════════════════
79
80/// First-order logic term representing entities or values.
81///
82/// Terms denote individuals, groups, or computed values in the domain
83/// of discourse. They serve as arguments to predicates.
84#[derive(Debug, Clone, Copy)]
85pub enum Term<'a> {
86 /// Named individual constant (e.g., `john`, `paris`).
87 Constant(Symbol),
88 /// Bound or free variable (e.g., `x`, `y`).
89 Variable(Symbol),
90 /// Function application: `f(t1, t2, ...)` (e.g., `mother(john)`).
91 Function(Symbol, &'a [Term<'a>]),
92 /// Plural group for collective readings (e.g., `john ⊕ mary`).
93 Group(&'a [Term<'a>]),
94 /// Possessive construction: `john's book` → `Poss(john, book)`.
95 Possessed {
96 possessor: &'a Term<'a>,
97 possessed: Symbol,
98 },
99 /// Definite description σ-term: `σx.P(x)` ("the unique x such that P").
100 Sigma(Symbol),
101 /// Intensional term (Montague up-arrow `^P`) for de dicto readings.
102 Intension(Symbol),
103 /// Kind term (`^Kind`) — a Carlson-style kind-denoting entity, distinct
104 /// from a Montague intension. Used for kind reference ("the dodo is extinct")
105 /// and as the base of a kind-level relational adjective ("dental procedure"
106 /// → `Pertains(x, ^Tooth)`; McNally & Boleda 2004, predicates of kinds).
107 Kind(Symbol),
108 /// Sentential complement (embedded clause as propositional argument).
109 Proposition(&'a LogicExpr<'a>),
110 /// Numeric value with optional unit and dimension.
111 Value {
112 kind: NumberKind,
113 unit: Option<Symbol>,
114 dimension: Option<Dimension>,
115 },
116}
117
118/// Degree-comparison relation for [`LogicExpr::Comparative`].
119///
120/// `Greater` is the strict comparative (`>`, "taller than"); `GreaterEqual` is the
121/// equative (`≥`, "as tall as" — at least as tall); `Equal` is the exact equative
122/// ("exactly as tall as").
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub enum ComparisonRelation {
125 Greater,
126 GreaterEqual,
127 Equal,
128}
129
130/// Quantifier types for first-order and generalized quantifiers.
131///
132/// Extends standard FOL with generalized quantifiers that cannot be
133/// expressed with ∀ and ∃ alone (e.g., "most", "few", "at least 3").
134#[derive(Debug, Clone, Copy, PartialEq, Eq)]
135pub enum QuantifierKind {
136 /// Universal: ∀x ("every", "all", "each").
137 Universal,
138 /// Existential: ∃x ("some", "a", "an").
139 Existential,
140 /// Proportional: "most X are Y" (>50% of domain).
141 Most,
142 /// Proportional: "few X are Y" (<expected proportion).
143 Few,
144 /// Vague large quantity: "many X are Y".
145 Many,
146 /// Exact count: "exactly n X are Y".
147 Cardinal(u32),
148 /// Lower bound: "at least n X are Y".
149 AtLeast(u32),
150 /// Upper bound: "at most n X are Y".
151 AtMost(u32),
152 /// Generic: "cats meow" (characterizing generalization).
153 Generic,
154 /// Infinitely many: ∃^∞x φ — φ holds of infinitely many x.
155 InfinitelyMany,
156 /// Finitely many: ∃^<∞x φ — φ holds of only finitely many x.
157 FinitelyMany,
158 /// All but finitely many: ∀^∞x φ — φ fails of only finitely many x.
159 AllButFinitelyMany,
160}
161
162impl QuantifierKind {
163 /// The quantifier a determiner binds by itself; `None` for `any`, which reads universally or
164 /// existentially by polarity, and for every token that is no determiner.
165 pub fn of_determiner(token: &TokenType) -> Option<QuantifierKind> {
166 Some(match token {
167 TokenType::All | TokenType::No => QuantifierKind::Universal,
168 TokenType::Some => QuantifierKind::Existential,
169 TokenType::Most => QuantifierKind::Most,
170 TokenType::Few => QuantifierKind::Few,
171 TokenType::Many => QuantifierKind::Many,
172 TokenType::Cardinal(n) => QuantifierKind::Cardinal(*n),
173 TokenType::AtLeast(n) => QuantifierKind::AtLeast(*n),
174 TokenType::AtMost(n) => QuantifierKind::AtMost(*n),
175 TokenType::InfinitelyMany => QuantifierKind::InfinitelyMany,
176 TokenType::FinitelyMany => QuantifierKind::FinitelyMany,
177 TokenType::AllButFinitelyMany => QuantifierKind::AllButFinitelyMany,
178 _ => return None,
179 })
180 }
181
182 /// Whether the restrictor implies the scope (`∀x(R → S)`) rather than conjoining with it
183 /// (`∃x(R ∧ S)`): a quantifier that speaks of every restrictor element, or of all but finitely
184 /// many of them.
185 pub fn restricts_by_implication(&self) -> bool {
186 matches!(
187 self,
188 QuantifierKind::Universal | QuantifierKind::AllButFinitelyMany
189 )
190 }
191}
192
193/// Binary logical connectives.
194#[derive(Debug, Clone, Copy, PartialEq, Eq)]
195pub enum BinaryOpKind {
196 /// Conjunction: P ∧ Q.
197 And,
198 /// Disjunction: P ∨ Q.
199 Or,
200 /// Material implication: P → Q.
201 Implies,
202 /// Biconditional: P ↔ Q.
203 Iff,
204}
205
206/// Unary logical operators.
207#[derive(Debug, Clone, Copy, PartialEq, Eq)]
208pub enum UnaryOpKind {
209 /// Negation: ¬P.
210 Not,
211}
212
213// ═══════════════════════════════════════════════════════════════════
214// Temporal & Aspect Operators (Arthur Prior's Tense Logic)
215// ═══════════════════════════════════════════════════════════════════
216
217/// Temporal logic operators.
218///
219/// Prior-style tense operators (Past, Future) for linguistic temporality.
220/// Pnueli-style LTL operators (Always, Eventually, Next) for hardware verification.
221#[derive(Debug, Clone, Copy, PartialEq, Eq)]
222pub enum TemporalOperator {
223 /// Past tense: P(φ) — "it was the case that φ".
224 Past,
225 /// Future tense: F(φ) — "it will be the case that φ".
226 Future,
227 /// Always/Globally: G(φ) — φ holds at every future state.
228 Always,
229 /// Eventually/Finally: F(φ) — φ holds at some future state.
230 Eventually,
231 /// Next: X(φ) — φ holds at the immediate next state.
232 Next,
233 /// Bounded Eventually: F≤n(φ) — φ holds within n steps.
234 /// SVA target: `##[0:n] φ`
235 BoundedEventually(u32),
236}
237
238/// Binary temporal operators (LTL).
239///
240/// These require two operands and express relationships between
241/// properties over time in hardware state machines.
242#[derive(Debug, Clone, Copy, PartialEq, Eq)]
243pub enum BinaryTemporalOp {
244 /// φ U ψ — φ holds until ψ becomes true.
245 Until,
246 /// φ R ψ — dual of Until: ψ holds until φ releases it (or forever).
247 Release,
248 /// φ W ψ — weak until: φ holds until ψ, or φ holds forever.
249 WeakUntil,
250}
251
252// ═══════════════════════════════════════════════════════════════════
253// Event Semantics (Neo-Davidsonian)
254// ═══════════════════════════════════════════════════════════════════
255
256/// Neo-Davidsonian thematic roles for event semantics.
257///
258/// Following Parsons' neo-Davidsonian analysis, events are reified and
259/// participants are related to events via thematic role predicates:
260/// `∃e(Run(e) ∧ Agent(e, john) ∧ Location(e, park))`.
261#[derive(Debug, Clone, Copy, PartialEq, Eq)]
262pub enum ThematicRole {
263 /// Animate initiator of action (e.g., "John" in "John ran").
264 Agent,
265 /// Entity affected by action (e.g., "the window" in "broke the window").
266 Patient,
267 /// Entity involved without change (e.g., "the ball" in "saw the ball").
268 Theme,
269 /// Animate entity receiving something (e.g., "Mary" in "gave Mary a book").
270 Recipient,
271 /// Destination or endpoint (e.g., "Paris" in "went to Paris").
272 Goal,
273 /// Origin or starting point (e.g., "London" in "came from London").
274 Source,
275 /// Tool or means (e.g., "a knife" in "cut with a knife").
276 Instrument,
277 /// Spatial setting (e.g., "the park" in "ran in the park").
278 Location,
279 /// Temporal setting (e.g., "yesterday" in "arrived yesterday").
280 Time,
281 /// How action was performed (e.g., "quickly" in "ran quickly").
282 Manner,
283 /// Resulting state of an argument — resultative secondary predication
284 /// (e.g., "red" in "painted the door red"): `Result(e, Red(door))`.
285 Result,
286 /// State an argument holds during the event — depictive secondary predication
287 /// (e.g., "raw" in "ate the meat raw"): `Depictive(e, Raw(meat))`.
288 Depictive,
289}
290
291impl ThematicRole {
292 /// Every role, in declaration order.
293 pub const ALL: [ThematicRole; 12] = [
294 ThematicRole::Agent,
295 ThematicRole::Patient,
296 ThematicRole::Theme,
297 ThematicRole::Recipient,
298 ThematicRole::Goal,
299 ThematicRole::Source,
300 ThematicRole::Instrument,
301 ThematicRole::Location,
302 ThematicRole::Time,
303 ThematicRole::Manner,
304 ThematicRole::Result,
305 ThematicRole::Depictive,
306 ];
307
308 /// The role's name as the formulas print it: `Agent(e, John)`.
309 pub fn name(self) -> &'static str {
310 match self {
311 ThematicRole::Agent => "Agent",
312 ThematicRole::Patient => "Patient",
313 ThematicRole::Theme => "Theme",
314 ThematicRole::Recipient => "Recipient",
315 ThematicRole::Goal => "Goal",
316 ThematicRole::Source => "Source",
317 ThematicRole::Instrument => "Instrument",
318 ThematicRole::Location => "Location",
319 ThematicRole::Time => "Time",
320 ThematicRole::Manner => "Manner",
321 ThematicRole::Result => "Result",
322 ThematicRole::Depictive => "Depictive",
323 }
324 }
325
326 /// The position of the role in [`ThematicRole::ALL`]. A new role does not compile until it
327 /// has one, and the `role_tests` then fail until `ALL` lists it.
328 pub fn index(self) -> usize {
329 match self {
330 ThematicRole::Agent => 0,
331 ThematicRole::Patient => 1,
332 ThematicRole::Theme => 2,
333 ThematicRole::Recipient => 3,
334 ThematicRole::Goal => 4,
335 ThematicRole::Source => 5,
336 ThematicRole::Instrument => 6,
337 ThematicRole::Location => 7,
338 ThematicRole::Time => 8,
339 ThematicRole::Manner => 9,
340 ThematicRole::Result => 10,
341 ThematicRole::Depictive => 11,
342 }
343 }
344}
345
346#[cfg(test)]
347#[path = "../../../logicaffeine_tests/unit/logicaffeine_language/ast/logic/role_tests.rs"]
348mod role_tests;
349
350/// Grammatical aspect operators for event structure.
351///
352/// Aspect describes the internal temporal structure of events,
353/// distinct from tense which locates events in time.
354#[derive(Debug, Clone, Copy, PartialEq, Eq)]
355pub enum AspectOperator {
356 /// Ongoing action: "is running" → PROG(Run(e)).
357 Progressive,
358 /// Completed with present relevance: "has eaten" → PERF(Eat(e)).
359 Perfect,
360 /// Characteristic pattern: "smokes" (habitually) → HAB(Smoke(e)).
361 Habitual,
362 /// Repeated action: "kept knocking" → ITER(Knock(e)).
363 Iterative,
364}
365
366/// Grammatical voice operators.
367#[derive(Debug, Clone, Copy, PartialEq, Eq)]
368pub enum VoiceOperator {
369 /// Passive voice: "was eaten" promotes patient to subject position.
370 Passive,
371}
372
373// ═══════════════════════════════════════════════════════════════════
374// Legacy Types (kept during transition)
375// ═══════════════════════════════════════════════════════════════════
376
377/// Parsed noun phrase structure for compositional interpretation.
378///
379/// Captures the internal structure of noun phrases including determiners,
380/// modifiers, and possessives for correct semantic composition.
381#[derive(Debug, Clone, Copy)]
382pub struct NounPhrase<'a> {
383 /// Definiteness: the (definite), a/an (indefinite), or bare (none).
384 pub definiteness: Option<Definiteness>,
385 /// Pre-nominal adjectives (e.g., "big red" in "big red ball").
386 pub adjectives: &'a [Symbol],
387 /// Head noun (e.g., "ball" in "big red ball").
388 pub noun: Symbol,
389 /// Possessor phrase (e.g., "John's" in "John's book").
390 pub possessor: Option<&'a NounPhrase<'a>>,
391 /// Prepositional phrase modifiers attached to noun.
392 pub pps: &'a [&'a LogicExpr<'a>],
393 /// Superlative adjective if present (e.g., "tallest").
394 pub superlative: Option<Symbol>,
395}
396
397// ═══════════════════════════════════════════════════════════════════
398// Boxed Variant Data (keeps LogicExpr enum small)
399// ═══════════════════════════════════════════════════════════════════
400
401/// Aristotelian categorical proposition data.
402///
403/// Represents the four categorical forms (A, E, I, O):
404/// - A: All S are P
405/// - E: No S are P
406/// - I: Some S are P
407/// - O: Some S are not P
408#[derive(Debug)]
409pub struct CategoricalData<'a> {
410 /// The quantifier (All, No, Some).
411 pub quantifier: TokenType,
412 /// Subject term (S in "All S are P").
413 pub subject: NounPhrase<'a>,
414 /// Whether copula is negated (for O-form: "Some S are not P").
415 pub copula_negative: bool,
416 /// Predicate term (P in "All S are P").
417 pub predicate: NounPhrase<'a>,
418}
419
420/// Simple subject-verb-object relation data.
421#[derive(Debug)]
422pub struct RelationData<'a> {
423 /// Subject noun phrase.
424 pub subject: NounPhrase<'a>,
425 /// Verb predicate.
426 pub verb: Symbol,
427 /// Object noun phrase.
428 pub object: NounPhrase<'a>,
429}
430
431/// Neo-Davidsonian event structure with thematic roles.
432///
433/// Represents a verb event with its participants decomposed into
434/// separate thematic role predicates: `∃e(Run(e) ∧ Agent(e, john))`.
435#[derive(Debug)]
436pub struct NeoEventData<'a> {
437 /// The event variable (e, e1, e2, ...).
438 pub event_var: Symbol,
439 /// The verb predicate name.
440 pub verb: Symbol,
441 /// Thematic role assignments: (Role, Filler) pairs.
442 pub roles: &'a [(ThematicRole, Term<'a>)],
443 /// Adverbial modifiers (e.g., "quickly" → Quickly(e)).
444 pub modifiers: &'a [Symbol],
445 /// When true, suppress local ∃e quantification.
446 /// Used in DRT for generic conditionals where event var is bound by outer ∀.
447 pub suppress_existential: bool,
448 /// World argument for Kripke semantics. None = implicit actual world (w₀).
449 pub world: Option<Symbol>,
450}
451
452impl<'a> NounPhrase<'a> {
453 pub fn simple(noun: Symbol) -> Self {
454 NounPhrase {
455 definiteness: None,
456 adjectives: &[],
457 noun,
458 possessor: None,
459 pps: &[],
460 superlative: None,
461 }
462 }
463
464 pub fn with_definiteness(definiteness: Definiteness, noun: Symbol) -> Self {
465 NounPhrase {
466 definiteness: Some(definiteness),
467 adjectives: &[],
468 noun,
469 possessor: None,
470 pps: &[],
471 superlative: None,
472 }
473 }
474}
475
476/// Modal logic domain classification.
477///
478/// Determines the accessibility relation in Kripke semantics:
479/// what kinds of possible worlds are relevant.
480#[derive(Debug, Clone, Copy, PartialEq)]
481pub enum ModalDomain {
482 /// Alethic modality: logical/metaphysical possibility and necessity.
483 /// "It is possible that P" = P holds in some accessible world.
484 Alethic,
485 /// Deontic modality: obligation and permission.
486 /// "It is obligatory that P" = P holds in all deontically ideal worlds.
487 Deontic,
488 /// Temporal modality: hardware state transitions.
489 /// Accessibility = next-state relation (clock-cycle transitions).
490 Temporal,
491}
492
493/// Modal flavor affecting scope interpretation.
494///
495/// The distinction between root and epistemic modals affects
496/// quantifier scope: root modals scope under quantifiers (de re),
497/// while epistemic modals scope over quantifiers (de dicto).
498#[derive(Debug, Clone, Copy, PartialEq, Eq)]
499pub enum ModalFlavor {
500 /// Root modals express ability, obligation, or circumstantial possibility.
501 /// Verbs: can, must, should, shall, could, would.
502 /// Scope: NARROW (de re) — modal attaches inside quantifier scope.
503 /// Example: "Every student can solve this" = ∀x(Student(x) → ◇Solve(x, this))
504 Root,
505 /// Epistemic modals express possibility or deduction based on evidence.
506 /// Verbs: might, may (epistemic readings).
507 /// Scope: WIDE (de dicto) — modal wraps the entire quantified formula.
508 /// Example: "A student might win" = ◇∃x(Student(x) ∧ Win(x))
509 Epistemic,
510 /// Evidential modality marks an evidence source without asserting the
511 /// complement: raising verbs seem/appear/look (§4.3).
512 /// Frame: serial, non-reflexive — Seem(⟨P⟩) does not entail P.
513 /// Example: "John seems happy" = Seem(⟨Happy(john)⟩)
514 Evidential,
515 /// Bouletic modality quantifies over preference-ideal worlds: wishes
516 /// (§1.2 optatives) and directives (§1.4 imperatives).
517 /// Frame: serial — the wished/commanded content is never entailed.
518 Bouletic,
519}
520
521/// Modal operator parameters for Kripke semantics (Kratzer-style).
522///
523/// Combines domain (what kind of modality), force (necessity vs possibility),
524/// and flavor (scope/evidence behavior) with the conversational backgrounds:
525/// a modal base f (which worlds are in play) and an ordering source g (how
526/// they are ranked). For evidentials the modal base names the evidence-source
527/// lexeme (seem/appear); counterfactuals use g = similarity.
528#[derive(Debug, Clone, Copy, PartialEq)]
529pub struct ModalVector {
530 /// The modal domain: alethic or deontic.
531 pub domain: ModalDomain,
532 /// Modal force: 1.0 = necessity (□), 0.5 = possibility (◇), graded values between.
533 pub force: f32,
534 /// Scope flavor: root (narrow scope) or epistemic (wide scope).
535 pub flavor: ModalFlavor,
536 /// Kratzer modal base f — the conversational background supplying the
537 /// accessible worlds (for evidentials: the evidence-source lexeme).
538 pub modal_base: Option<Symbol>,
539 /// Kratzer ordering source g — ranks the modal-base worlds by ideality /
540 /// normality / similarity.
541 pub ordering_source: Option<Symbol>,
542}
543
544impl ModalVector {
545 /// A modal vector with empty conversational backgrounds (f = g = None).
546 pub fn new(domain: ModalDomain, force: f32, flavor: ModalFlavor) -> Self {
547 ModalVector {
548 domain,
549 force,
550 flavor,
551 modal_base: None,
552 ordering_source: None,
553 }
554 }
555
556 /// Attach a Kratzer modal base f.
557 pub fn with_base(mut self, base: Symbol) -> Self {
558 self.modal_base = Some(base);
559 self
560 }
561}
562
563// ═══════════════════════════════════════════════════════════════════
564// Expression Enum (hybrid: old + new variants)
565// ═══════════════════════════════════════════════════════════════════
566
567/// First-order logic expression with modal, temporal, and event extensions.
568///
569/// This is the core AST type representing logical formulas. All nodes are
570/// arena-allocated with the `'a` lifetime tracking the arena's scope.
571///
572/// # Categories
573///
574/// - **Core FOL**: [`Predicate`], [`Quantifier`], [`BinaryOp`], [`UnaryOp`], [`Identity`]
575/// - **Lambda calculus**: [`Lambda`], [`App`], [`Atom`]
576/// - **Modal logic**: [`Modal`], [`Intensional`]
577/// - **Temporal/Aspect**: [`Temporal`], [`Aspectual`], [`Voice`]
578/// - **Event semantics**: [`Event`], [`NeoEvent`]
579/// - **Questions**: [`Question`], [`YesNoQuestion`]
580/// - **Pragmatics**: [`SpeechAct`], [`Focus`], [`Presupposition`]
581/// - **Comparison**: [`Comparative`], [`Superlative`]
582/// - **Other**: [`Counterfactual`], [`Causal`], [`Control`], [`Imperative`]
583///
584/// [`Predicate`]: LogicExpr::Predicate
585/// [`Quantifier`]: LogicExpr::Quantifier
586/// [`BinaryOp`]: LogicExpr::BinaryOp
587/// [`UnaryOp`]: LogicExpr::UnaryOp
588/// [`Identity`]: LogicExpr::Identity
589/// [`Lambda`]: LogicExpr::Lambda
590/// [`App`]: LogicExpr::App
591/// [`Atom`]: LogicExpr::Atom
592/// [`Modal`]: LogicExpr::Modal
593/// [`Intensional`]: LogicExpr::Intensional
594/// [`Temporal`]: LogicExpr::Temporal
595/// [`Aspectual`]: LogicExpr::Aspectual
596/// [`Voice`]: LogicExpr::Voice
597/// [`Event`]: LogicExpr::Event
598/// [`NeoEvent`]: LogicExpr::NeoEvent
599/// [`Question`]: LogicExpr::Question
600/// [`YesNoQuestion`]: LogicExpr::YesNoQuestion
601/// [`SpeechAct`]: LogicExpr::SpeechAct
602/// [`Focus`]: LogicExpr::Focus
603/// [`Presupposition`]: LogicExpr::Presupposition
604/// [`Comparative`]: LogicExpr::Comparative
605/// [`Superlative`]: LogicExpr::Superlative
606/// [`Counterfactual`]: LogicExpr::Counterfactual
607/// [`Causal`]: LogicExpr::Causal
608/// [`Control`]: LogicExpr::Control
609/// [`Imperative`]: LogicExpr::Imperative
610#[derive(Debug)]
611pub enum LogicExpr<'a> {
612 /// Atomic predicate: `P(t1, t2, ...)` with optional world parameter.
613 Predicate {
614 name: Symbol,
615 args: &'a [Term<'a>],
616 /// World argument for Kripke semantics. None = implicit actual world (w₀).
617 world: Option<Symbol>,
618 },
619
620 /// Identity statement: `t1 = t2`.
621 Identity {
622 left: &'a Term<'a>,
623 right: &'a Term<'a>,
624 },
625
626 /// Metaphorical assertion: tenor "is" vehicle (non-literal identity).
627 Metaphor {
628 tenor: &'a Term<'a>,
629 vehicle: &'a Term<'a>,
630 },
631
632 /// Quantified formula: `∀x.φ` or `∃x.φ` with scope island tracking.
633 Quantifier {
634 kind: QuantifierKind,
635 variable: Symbol,
636 body: &'a LogicExpr<'a>,
637 /// Island ID prevents illicit scope interactions across syntactic boundaries.
638 island_id: u32,
639 },
640
641 /// Aristotelian categorical proposition (boxed to keep enum small).
642 Categorical(Box<CategoricalData<'a>>),
643
644 /// Simple S-V-O relation (boxed).
645 Relation(Box<RelationData<'a>>),
646
647 /// Modal operator: □φ (necessity) or ◇φ (possibility).
648 Modal {
649 vector: ModalVector,
650 operand: &'a LogicExpr<'a>,
651 },
652
653 /// Tense/temporal operator: PAST(φ), FUTURE(φ), ALWAYS(φ), EVENTUALLY(φ), NEXT(φ).
654 Temporal {
655 operator: TemporalOperator,
656 body: &'a LogicExpr<'a>,
657 },
658
659 /// Binary temporal operator: φ UNTIL ψ, φ RELEASE ψ, φ WEAKUNTIL ψ.
660 TemporalBinary {
661 operator: BinaryTemporalOp,
662 left: &'a LogicExpr<'a>,
663 right: &'a LogicExpr<'a>,
664 },
665
666 /// Aspect operator: PROG(φ), PERF(φ), HAB(φ), ITER(φ).
667 Aspectual {
668 operator: AspectOperator,
669 body: &'a LogicExpr<'a>,
670 },
671
672 /// Voice operator: PASSIVE(φ).
673 Voice {
674 operator: VoiceOperator,
675 body: &'a LogicExpr<'a>,
676 },
677
678 /// Binary connective: φ ∧ ψ, φ ∨ ψ, φ → ψ, φ ↔ ψ.
679 BinaryOp {
680 left: &'a LogicExpr<'a>,
681 op: TokenType,
682 right: &'a LogicExpr<'a>,
683 },
684
685 /// Unary operator: ¬φ.
686 UnaryOp {
687 op: TokenType,
688 operand: &'a LogicExpr<'a>,
689 },
690
691 /// Wh-question: λx.φ where x is the questioned variable.
692 Question {
693 wh_variable: Symbol,
694 body: &'a LogicExpr<'a>,
695 },
696
697 /// Yes/no question: ?φ (is φ true?).
698 YesNoQuestion { body: &'a LogicExpr<'a> },
699
700 /// Atomic symbol (variable or constant in lambda context).
701 Atom(Symbol),
702
703 /// Lambda abstraction: λx.φ.
704 Lambda {
705 variable: Symbol,
706 body: &'a LogicExpr<'a>,
707 },
708
709 /// Function application: (φ)(ψ).
710 App {
711 function: &'a LogicExpr<'a>,
712 argument: &'a LogicExpr<'a>,
713 },
714
715 /// Intensional context: `operator[content]` for opaque verbs (believes, seeks).
716 Intensional {
717 operator: Symbol,
718 content: &'a LogicExpr<'a>,
719 },
720
721 /// Legacy event semantics (Davidson-style with adverb list).
722 Event {
723 predicate: &'a LogicExpr<'a>,
724 adverbs: &'a [Symbol],
725 },
726
727 /// Neo-Davidsonian event with thematic roles (boxed).
728 NeoEvent(Box<NeoEventData<'a>>),
729
730 /// Imperative command: !φ.
731 Imperative { action: &'a LogicExpr<'a> },
732
733 /// Exclamative: affective stance toward a surprisingly-high degree, with no
734 /// subject-aux inversion ("How tall she is!", "What a fool he is!"). Asserts
735 /// `∃degree_var(body ∧ degree_var ≫ θ)` and presupposes `body`.
736 Exclamative {
737 degree_var: Symbol,
738 body: &'a LogicExpr<'a>,
739 },
740
741 /// Optative: a wish with no asserted truth ("May you prosper!", "Long live the
742 /// king!", "If only it were Friday!"). → `Wish(speaker, ⟨wish⟩)`; the complement
743 /// is NOT entailed.
744 Optative { wish: &'a LogicExpr<'a> },
745
746 /// Scalar implicature (§8.7): a weak scalar item asserts `assertion` and
747 /// DEFEASIBLY implicates `implicature` (the negation of a stronger Horn
748 /// alternative). "Some students passed." → ∃… +> ¬∀…. Rendered `assertion +>
749 /// implicature`; the implicature is cancellable and not part of truth conditions.
750 Implicature {
751 assertion: &'a LogicExpr<'a>,
752 implicature: &'a LogicExpr<'a>,
753 },
754
755 /// Speech act: performative utterance with illocutionary force.
756 SpeechAct {
757 performer: Symbol,
758 act_type: Symbol,
759 content: &'a LogicExpr<'a>,
760 },
761
762 /// Counterfactual conditional: "If P had been, Q would have been".
763 Counterfactual {
764 antecedent: &'a LogicExpr<'a>,
765 consequent: &'a LogicExpr<'a>,
766 },
767
768 /// Causal relation: "effect because cause".
769 Causal {
770 effect: &'a LogicExpr<'a>,
771 cause: &'a LogicExpr<'a>,
772 },
773
774 /// Concessive relation: "main, although concession" — the main clause holds
775 /// DESPITE a defeated expectation from the concession ("Although she was tired,
776 /// she finished." → Finish(she) ∧ Concessive(Tired(she))).
777 Concessive {
778 main: &'a LogicExpr<'a>,
779 concession: &'a LogicExpr<'a>,
780 },
781
782 /// Comparative / equative: "X is taller than Y" (`>`), "X is as tall as Y"
783 /// (`≥`), "X is as tall as Y and no taller" (`=`). The `relation` selects the
784 /// degree comparison; `difference` is the optional measure ("by 2 inches").
785 Comparative {
786 adjective: Symbol,
787 subject: &'a Term<'a>,
788 object: &'a Term<'a>,
789 difference: Option<&'a Term<'a>>,
790 relation: ComparisonRelation,
791 },
792
793 /// Superlative: "X is the tallest among domain".
794 Superlative {
795 adjective: Symbol,
796 subject: &'a Term<'a>,
797 domain: Symbol,
798 },
799
800 /// Scopal adverb: "only", "always", etc. as operators.
801 Scopal {
802 operator: Symbol,
803 body: &'a LogicExpr<'a>,
804 },
805
806 /// Control verb: "wants to VP", "persuaded X to VP".
807 Control {
808 verb: Symbol,
809 subject: &'a Term<'a>,
810 object: Option<&'a Term<'a>>,
811 infinitive: &'a LogicExpr<'a>,
812 },
813
814 /// Presupposition-assertion structure.
815 Presupposition {
816 assertion: &'a LogicExpr<'a>,
817 presupposition: &'a LogicExpr<'a>,
818 },
819
820 /// Focus particle: "only X", "even X" with alternative set.
821 Focus {
822 kind: crate::token::FocusKind,
823 focused: &'a Term<'a>,
824 scope: &'a LogicExpr<'a>,
825 },
826
827 /// Temporal anchor: "yesterday(φ)", "now(φ)".
828 TemporalAnchor {
829 anchor: Symbol,
830 body: &'a LogicExpr<'a>,
831 },
832
833 /// Distributive operator: *P distributes P over group members.
834 Distributive { predicate: &'a LogicExpr<'a> },
835
836 /// Group quantifier for collective cardinal readings.
837 /// `∃g(Group(g) ∧ Count(g,n) ∧ ∀x(Member(x,g) → Restriction(x)) ∧ Body(g))`
838 GroupQuantifier {
839 group_var: Symbol,
840 count: u32,
841 member_var: Symbol,
842 restriction: &'a LogicExpr<'a>,
843 body: &'a LogicExpr<'a>,
844 },
845}
846
847impl<'a> LogicExpr<'a> {
848 pub fn lambda(
849 var: Symbol,
850 body: &'a LogicExpr<'a>,
851 arena: &'a Arena<LogicExpr<'a>>,
852 ) -> &'a LogicExpr<'a> {
853 arena.alloc(LogicExpr::Lambda {
854 variable: var,
855 body,
856 })
857 }
858
859 pub fn app(
860 func: &'a LogicExpr<'a>,
861 arg: &'a LogicExpr<'a>,
862 arena: &'a Arena<LogicExpr<'a>>,
863 ) -> &'a LogicExpr<'a> {
864 arena.alloc(LogicExpr::App {
865 function: func,
866 argument: arg,
867 })
868 }
869}
870
871#[cfg(test)]
872#[path = "../../../logicaffeine_tests/unit/logicaffeine_language/ast/logic/size_tests.rs"]
873mod size_tests;