simple_semantics/
language.rs

1//! Defines the core language of thought of the model and a simple virtual machine.
2
3use std::fmt::Display;
4
5#[cfg(not(target_arch = "wasm32"))]
6use std::time::{Duration, Instant};
7
8use crate::lambda::RootedLambdaPool;
9use crate::lambda::types::LambdaType;
10use crate::{Actor, Entity, Event, PropertyLabel, Scenario};
11
12use itertools::Either;
13use thiserror;
14
15///All binary operations
16#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord)]
17pub enum BinOp {
18    ///<a,<e,t>> function that returns whether the first argument is the agent of the second
19    ///argument.
20    AgentOf,
21    ///<a,<e,t>> function that returns whether the first argument is the patient of the second
22    ///argument.
23    PatientOf,
24    ///Logical AND
25    And,
26    ///Logical OR
27    Or,
28}
29
30impl Display for BinOp {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        write!(
33            f,
34            "{}",
35            match self {
36                BinOp::AgentOf => "AgentOf",
37                BinOp::PatientOf => "PatientOf",
38                BinOp::And => "&",
39                BinOp::Or => "|",
40            }
41        )
42    }
43}
44
45impl BinOp {
46    fn get_argument_type(&self) -> [&LambdaType; 2] {
47        match self {
48            BinOp::AgentOf | BinOp::PatientOf => [LambdaType::a(), LambdaType::e()],
49            BinOp::And | BinOp::Or => [LambdaType::t(), LambdaType::t()],
50        }
51    }
52}
53
54#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)]
55///All unary operations
56pub enum MonOp<'a> {
57    ///Logical not
58    Not,
59    ///Returns whether an actor or event is a member of a predicate defined by the label.
60    Property(PropertyLabel<'a>, ActorOrEvent),
61
62    ///Takes an actor or event predicate and returns the one present example that has it.
63    Iota(ActorOrEvent),
64}
65
66impl MonOp<'_> {
67    fn get_argument_type(&self) -> &LambdaType {
68        match self {
69            MonOp::Property(_, ActorOrEvent::Actor) => LambdaType::a(),
70            MonOp::Property(_, ActorOrEvent::Event) => LambdaType::e(),
71            MonOp::Iota(ActorOrEvent::Actor | ActorOrEvent::Event) | MonOp::Not => LambdaType::t(),
72        }
73    }
74}
75
76impl Display for MonOp<'_> {
77    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78        match self {
79            MonOp::Not => write!(f, "~"),
80            MonOp::Property(x, ActorOrEvent::Actor) => write!(f, "pa_{x}"),
81            MonOp::Property(x, ActorOrEvent::Event) => write!(f, "pe_{x}"),
82            MonOp::Iota(ActorOrEvent::Actor) => write!(f, "iota"),
83            MonOp::Iota(ActorOrEvent::Event) => write!(f, "iota_e"),
84        }
85    }
86}
87
88///Whether something refers to an actor or event.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
90#[allow(missing_docs)]
91pub enum ActorOrEvent {
92    Actor,
93    Event,
94}
95
96impl Display for ActorOrEvent {
97    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98        match self {
99            ActorOrEvent::Actor => write!(f, "a"),
100            ActorOrEvent::Event => write!(f, "e"),
101        }
102    }
103}
104
105impl From<ActorOrEvent> for LambdaType {
106    fn from(value: ActorOrEvent) -> Self {
107        match value {
108            ActorOrEvent::Actor => LambdaType::A,
109            ActorOrEvent::Event => LambdaType::E,
110        }
111    }
112}
113
114///Any valid constant in the language.
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
116pub enum Constant<'a> {
117    ///The set of all actors in the [`Scenario`].
118    Everyone,
119    ///The set of all events in the [`Scenario`].
120    EveryEvent,
121    ///Truth
122    Tautology,
123    ///Falsity
124    Contradiction,
125    ///Any predicate as a set
126    Property(PropertyLabel<'a>, ActorOrEvent),
127}
128
129impl Display for Constant<'_> {
130    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131        match self {
132            Constant::Everyone => write!(f, "all_a"),
133            Constant::EveryEvent => write!(f, "all_e"),
134            Constant::Tautology => write!(f, "True"),
135            Constant::Contradiction => write!(f, "False"),
136            Constant::Property(x, ActorOrEvent::Actor) => write!(f, "pa_{x}"),
137            Constant::Property(x, ActorOrEvent::Event) => write!(f, "pe_{x}"),
138        }
139    }
140}
141
142///The ID of a given variable bound by quantification
143#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord)]
144pub enum Variable {
145    ///The variable is over actors.
146    Actor(u32),
147    ///The variable is over events.
148    Event(u32),
149}
150
151impl Variable {
152    fn id(self) -> u32 {
153        match self {
154            Variable::Actor(a) | Variable::Event(a) => a,
155        }
156    }
157
158    fn as_lambda_type(self) -> &'static LambdaType {
159        match self {
160            Variable::Actor(_) => LambdaType::a(),
161            Variable::Event(_) => LambdaType::e(),
162        }
163    }
164}
165
166///An enum which represents all possible quantifiers in the language.
167#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord)]
168pub enum Quantifier {
169    ///Universal Quantification
170    Universal,
171    ///Existential quantification
172    Existential,
173}
174
175impl Display for Quantifier {
176    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
177        match self {
178            Quantifier::Universal => write!(f, "every"),
179            Quantifier::Existential => write!(f, "some"),
180        }
181    }
182}
183
184///The basic expression type of the language of thought.
185///Note that it *does not* include free variables or any of the machinery of the lambda calculus
186///which is handled elsewhere.
187#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord)]
188pub enum Expr<'a> {
189    ///A quantified expression. Variables are implemented with `DeBruijn` indices.
190    Quantifier {
191        ///What kind of quantifier
192        quantifier: Quantifier,
193        ///The type of bound variable
194        var_type: ActorOrEvent,
195        ///An expression defining the restrictor of the quantifier.
196        restrictor: ExprRef,
197        ///An expression defining the subformula of the quantifier.
198        subformula: ExprRef,
199    },
200    ///See [`Variable`]
201    Variable(Variable),
202    ///See [`Actor`]. Written `a_NAME`
203    Actor(Actor<'a>),
204    ///See [`Event`]. Written `e_N` where `N` is an integer.
205    Event(Event),
206    ///Any binary function.
207    Binary(BinOp, ExprRef, ExprRef),
208    ///Any unary function.
209    Unary(MonOp<'a>, ExprRef),
210    ///All constants.
211    Constant(Constant<'a>),
212}
213
214///An index for a specific [`Expr`] in a [`LanguageExpression`]
215#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord)]
216pub struct ExprRef(pub u32);
217
218///An arena allocated tree which represents an expression in the language of thought built out of
219///[`Expr`].
220#[derive(Debug, Clone, Default, Eq, PartialEq, Hash)]
221pub(crate) struct ExprPool<'a>(Vec<Expr<'a>>);
222
223///An expression pool with a defined root.
224#[derive(Debug, Clone, Eq, PartialEq, Hash)]
225pub struct LanguageExpression<'a> {
226    pool: ExprPool<'a>,
227    start: ExprRef,
228}
229
230impl Display for LanguageExpression<'_> {
231    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232        let x: RootedLambdaPool<Expr> = self.clone().into();
233        write!(f, "{x}")
234    }
235}
236
237#[derive(Debug, Clone, Default, Copy, Eq, PartialEq, PartialOrd, Ord)]
238///A configuration struct to limit the time of execution of a given language expression
239pub struct ExecutionConfig {
240    max_steps: Option<usize>,
241    #[cfg(not(target_arch = "wasm32"))]
242    timeout: Option<Duration>,
243    empty_quantification: bool,
244}
245
246impl ExecutionConfig {
247    ///Create a new [`ExecutionConfig`]
248    #[must_use]
249    pub const fn new(
250        max_steps: Option<usize>,
251        #[cfg(not(target_arch = "wasm32"))] timeout: Option<Duration>,
252    ) -> Self {
253        ExecutionConfig {
254            max_steps,
255            #[cfg(not(target_arch = "wasm32"))]
256            timeout,
257            empty_quantification: false,
258        }
259    }
260
261    ///Forbid quantification over an empty set
262    #[must_use]
263    pub const fn forbid_empty_quantification(mut self) -> Self {
264        self.empty_quantification = false;
265        self
266    }
267
268    ///Allow quantification over an empty set
269    #[must_use]
270    pub const fn allow_empty_quantification(mut self) -> Self {
271        self.empty_quantification = true;
272        self
273    }
274
275    ///Set `max_steps` on a config
276    #[must_use]
277    pub const fn with_max_steps(mut self, max_steps: usize) -> Self {
278        self.max_steps = Some(max_steps);
279        self
280    }
281
282    ///Set `max_duration` on a config
283    #[cfg(not(target_arch = "wasm32"))]
284    #[must_use]
285    pub const fn with_timeout(mut self, time_out: Duration) -> Self {
286        self.timeout = Some(time_out);
287        self
288    }
289}
290
291impl<'a> LanguageExpression<'a> {
292    ///Run a [`LanguageExpression`] in the language of thought and return the [`LanguageResult`]
293    ///
294    ///# Errors
295    ///Will return a [`LanguageTypeError`] if the [`LanguageExpression`] is malformed, the code
296    ///times out or runs for too many steps according to the config, or if there is a
297    ///presupposition error. See [`LanguageTypeError`]
298    pub fn run(
299        &self,
300        scenario: &Scenario<'a>,
301        config: Option<ExecutionConfig>,
302    ) -> Result<LanguageResult<'a>, LanguageTypeError> {
303        let mut variables = VariableBuffer::default();
304        Execution {
305            pool: &self.pool,
306            n_steps: 0,
307
308            #[cfg(not(target_arch = "wasm32"))]
309            start: Instant::now(),
310
311            config: &config.unwrap_or_default(),
312            quantifier_depth: 0,
313        }
314        .interp(self.start, scenario, &mut variables)
315    }
316
317    ///Parse a given language of thought expression and return the [`LanguageExpression`]. This
318    ///does not support tools from the lambda calculus, see [`RootedLambdaPool`].
319    ///
320    ///# Errors
321    ///Will return a [`LambdaParseError`]  if the language of thought expression has any
322    ///lambda terms or if it is malformed
323    pub fn parse(s: &'a str) -> Result<LanguageExpression<'a>, LambdaParseError> {
324        Ok(RootedLambdaPool::parse(s)?.into_pool()?)
325    }
326
327    #[allow(dead_code)]
328    ///Create a `LanguageExpression` out of a [`ExprRef`] and a [`ExprPool`]
329    pub(crate) fn new(pool: ExprPool<'a>, start: ExprRef) -> Self {
330        LanguageExpression { pool, start }
331    }
332}
333
334struct Execution<'a, 'b> {
335    pool: &'b ExprPool<'a>,
336    n_steps: usize,
337    #[cfg(not(target_arch = "wasm32"))]
338    start: Instant,
339    config: &'b ExecutionConfig,
340
341    quantifier_depth: usize,
342}
343
344impl Execution<'_, '_> {
345    fn check_if_good_to_continue(&mut self) -> Result<(), LanguageTypeError> {
346        if let Some(max_steps) = self.config.max_steps
347            && self.n_steps > max_steps
348        {
349            return Err(LanguageTypeError::TooManySteps(max_steps));
350        }
351
352        #[cfg(not(target_arch = "wasm32"))]
353        if let Some(max_time) = self.config.timeout
354            && self.start.elapsed() > max_time
355        {
356            return Err(LanguageTypeError::TimeOut);
357        }
358
359        self.n_steps += 1;
360        Ok(())
361    }
362}
363
364#[derive(Debug, Clone, PartialEq, Eq, Default, Hash)]
365struct VariableBuffer<'a>(Vec<Option<Entity<'a>>>);
366
367impl<'a> VariableBuffer<'a> {
368    fn set(&mut self, i: usize, x: Entity<'a>) {
369        if self.0.len() <= i {
370            self.0.resize(i + 1, None);
371        }
372        self.0[i] = Some(x);
373    }
374
375    fn get(&self, v: Variable, quantifier_depth: usize) -> Option<LanguageResult<'a>> {
376        let pos = (quantifier_depth).checked_sub(v.id() as usize + 1)?;
377        match self.0.get(pos) {
378            Some(x) => match (v, x) {
379                (Variable::Actor(_), Some(Entity::Actor(a))) => Some(LanguageResult::Actor(a)),
380                (Variable::Event(_), Some(Entity::Event(e))) => Some(LanguageResult::Event(*e)),
381                _ => None,
382            },
383            None => None,
384        }
385    }
386}
387
388///The result of running a [`LanguageExpression`], see [`LanguageExpression::run`].
389#[derive(Debug, Clone, PartialEq, Eq, Hash)]
390#[allow(missing_docs)]
391pub enum LanguageResult<'a> {
392    Bool(bool),
393    Actor(Actor<'a>),
394    Event(Event),
395    ///A set of actors (represented as a vector).
396    ActorSet(Vec<Actor<'a>>),
397    ///A set of events (represented as a vector).
398    EventSet(Vec<Event>),
399}
400
401impl LanguageResult<'_> {
402    fn to_language_result_type(&self) -> LanguageResultType {
403        match self {
404            LanguageResult::Bool(_) => LanguageResultType::Bool,
405            LanguageResult::Actor(_) => LanguageResultType::Actor,
406            LanguageResult::Event(_) => LanguageResultType::Event,
407            LanguageResult::ActorSet(_) => LanguageResultType::ActorSet,
408            LanguageResult::EventSet(_) => LanguageResultType::EventSet,
409        }
410    }
411}
412
413impl Display for LanguageResult<'_> {
414    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
415        match self {
416            LanguageResult::Bool(b) => write!(f, "{b}"),
417            LanguageResult::Actor(a) => write!(f, "a_{a}"),
418            LanguageResult::Event(e) => write!(f, "e_{e}"),
419            LanguageResult::ActorSet(items) => {
420                write!(
421                    f,
422                    "{{{}}}",
423                    items
424                        .iter()
425                        .map(|x| format!("a_{x}"))
426                        .collect::<Vec<_>>()
427                        .join(", ")
428                )
429            }
430            LanguageResult::EventSet(items) => write!(
431                f,
432                "{{{}}}",
433                items
434                    .iter()
435                    .map(|x| format!("e{x}"))
436                    .collect::<Vec<_>>()
437                    .join(", ")
438            ),
439        }
440    }
441}
442
443///The basic atomic types of the LOT. See [`LanguageResult`].
444#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
445#[allow(missing_docs)]
446pub enum LanguageResultType {
447    Bool,
448    Actor,
449    ActorSet,
450    Event,
451    EventSet,
452}
453
454impl Display for LanguageResultType {
455    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
456        write!(
457            f,
458            "{}",
459            match self {
460                LanguageResultType::Bool => "t",
461                LanguageResultType::Actor => "a",
462                LanguageResultType::ActorSet => "<a,t>",
463                LanguageResultType::Event => "e",
464                LanguageResultType::EventSet => "<e,t>",
465            }
466        )
467    }
468}
469
470///Possible errors that can be generated when running a [`LanguageExpression`]
471#[derive(Error, Debug, Copy, Clone, PartialEq, Eq)]
472pub enum LanguageTypeError {
473    ///A presupposition error in the semantics; occurs when a non-existent entity is referenced.
474    #[error("The referenced object does not exist in the current scenario")]
475    PresuppositionError,
476
477    ///A variable that is not bound that was used.
478    #[error("The referenced variable ({0:?}) does not exist in the current scenario")]
479    MissingVariable(Variable),
480
481    ///A type conversion which is violated.
482    #[error("Can't convert from {input} to {output}")]
483    WrongType {
484        ///The input type of the conversion
485        input: LanguageResultType,
486        ///The output type of the conversion
487        output: LanguageResultType,
488    },
489
490    ///The execution ran out of steps
491    #[error("The execution took more than {0} steps")]
492    TooManySteps(usize),
493
494    ///The execution ran out of time (unavailable on wasm).
495    #[error("The execution ran out of time")]
496    TimeOut,
497}
498
499impl TryFrom<LanguageResult<'_>> for Event {
500    type Error = LanguageTypeError;
501
502    fn try_from(value: LanguageResult) -> Result<Self, Self::Error> {
503        match value {
504            LanguageResult::Event(x) => Ok(x),
505            _ => Err(LanguageTypeError::WrongType {
506                input: value.to_language_result_type(),
507                output: LanguageResultType::Event,
508            }),
509        }
510    }
511}
512
513impl<'a> TryFrom<LanguageResult<'a>> for Actor<'a> {
514    type Error = LanguageTypeError;
515
516    fn try_from(value: LanguageResult<'a>) -> Result<Self, Self::Error> {
517        match value {
518            LanguageResult::Actor(x) => Ok(x),
519            _ => Err(LanguageTypeError::WrongType {
520                input: value.to_language_result_type(),
521                output: LanguageResultType::Actor,
522            }),
523        }
524    }
525}
526
527impl TryFrom<LanguageResult<'_>> for bool {
528    type Error = LanguageTypeError;
529
530    fn try_from(value: LanguageResult) -> Result<Self, Self::Error> {
531        match value {
532            LanguageResult::Bool(x) => Ok(x),
533            _ => Err(LanguageTypeError::WrongType {
534                input: value.to_language_result_type(),
535                output: LanguageResultType::Bool,
536            }),
537        }
538    }
539}
540
541impl<'a> TryFrom<LanguageResult<'a>> for Vec<Actor<'a>> {
542    type Error = LanguageTypeError;
543
544    fn try_from(value: LanguageResult<'a>) -> Result<Self, Self::Error> {
545        match value {
546            LanguageResult::ActorSet(x) => Ok(x),
547            _ => Err(LanguageTypeError::WrongType {
548                input: value.to_language_result_type(),
549                output: LanguageResultType::ActorSet,
550            }),
551        }
552    }
553}
554
555impl TryFrom<LanguageResult<'_>> for Vec<Event> {
556    type Error = LanguageTypeError;
557
558    fn try_from(value: LanguageResult) -> Result<Self, Self::Error> {
559        match value {
560            LanguageResult::EventSet(x) => Ok(x),
561            _ => Err(LanguageTypeError::WrongType {
562                input: value.to_language_result_type(),
563                output: LanguageResultType::EventSet,
564            }),
565        }
566    }
567}
568
569impl<'a> From<Vec<Expr<'a>>> for ExprPool<'a> {
570    fn from(value: Vec<Expr<'a>>) -> Self {
571        ExprPool(value)
572    }
573}
574
575impl<'a> ExprPool<'a> {
576    fn get(&self, expr: ExprRef) -> &Expr<'a> {
577        &self.0[expr.0 as usize]
578    }
579
580    fn get_type(&self, expr: ExprRef) -> LanguageResultType {
581        match self.get(expr) {
582            Expr::Variable(Variable::Actor(_)) | Expr::Actor(_) => LanguageResultType::Actor,
583            Expr::Variable(Variable::Event(_)) | Expr::Event(_) => LanguageResultType::Event,
584            Expr::Quantifier { .. } | Expr::Binary(..) | Expr::Unary(..) => {
585                LanguageResultType::Bool
586            }
587            Expr::Constant(constant) => match constant {
588                Constant::Everyone | Constant::Property(_, ActorOrEvent::Actor) => {
589                    LanguageResultType::ActorSet
590                }
591                Constant::EveryEvent | Constant::Property(_, ActorOrEvent::Event) => {
592                    LanguageResultType::EventSet
593                }
594                Constant::Tautology | Constant::Contradiction => LanguageResultType::Bool,
595            },
596        }
597    }
598}
599
600impl<'a> Execution<'a, '_> {
601    fn quantification(
602        &mut self,
603        quantifier: Quantifier,
604        var_type: ActorOrEvent,
605        restrictor: ExprRef,
606        subformula: ExprRef,
607        scenario: &Scenario<'a>,
608        variables: &mut VariableBuffer<'a>,
609    ) -> Result<LanguageResult<'a>, LanguageTypeError> {
610        self.quantifier_depth += 1;
611        let mut variables = variables.clone();
612        let domain: Vec<Entity> = match self.pool.get_type(restrictor) {
613            LanguageResultType::Bool => {
614                let mut domain = vec![];
615                match var_type {
616                    ActorOrEvent::Actor => {
617                        for e in &scenario.actors {
618                            variables.set(self.quantifier_depth - 1, Entity::Actor(e));
619                            let truth_value_for_e: bool = self
620                                .interp(restrictor, scenario, &mut variables)?
621                                .try_into()?;
622                            if truth_value_for_e {
623                                domain.push(Entity::Actor(e));
624                            }
625                        }
626                    }
627                    ActorOrEvent::Event => {
628                        for e in scenario.events() {
629                            variables.set(self.quantifier_depth - 1, Entity::Event(e));
630                            let truth_value_for_e: bool = self
631                                .interp(restrictor, scenario, &mut variables)?
632                                .try_into()?;
633                            if truth_value_for_e {
634                                domain.push(Entity::Event(e));
635                            }
636                        }
637                    }
638                }
639                domain
640            }
641            LanguageResultType::Actor => {
642                let e: Actor = self
643                    .interp(restrictor, scenario, &mut variables)?
644                    .try_into()?;
645                vec![Entity::Actor(e)]
646            }
647            LanguageResultType::ActorSet => {
648                let a: Vec<Actor> = self
649                    .interp(restrictor, scenario, &mut variables)?
650                    .try_into()?;
651                a.into_iter().map(Entity::Actor).collect()
652            }
653            LanguageResultType::Event => {
654                let e: Event = self
655                    .interp(restrictor, scenario, &mut variables)?
656                    .try_into()?;
657                vec![Entity::Event(e)]
658            }
659            LanguageResultType::EventSet => {
660                let a: Vec<Event> = self
661                    .interp(restrictor, scenario, &mut variables)?
662                    .try_into()?;
663                a.into_iter().map(Entity::Event).collect()
664            }
665        };
666
667        if !self.config.empty_quantification && domain.is_empty() {
668            return Err(LanguageTypeError::PresuppositionError);
669        }
670
671        let mut result = match quantifier {
672            Quantifier::Universal => true,
673            Quantifier::Existential => false,
674        };
675        let mut updated = false;
676        let mut error_found = false;
677        for e in domain {
678            variables.set(self.quantifier_depth - 1, e);
679            match self.interp(subformula, scenario, &mut variables) {
680                Ok(LanguageResult::Bool(subformula_value)) => {
681                    updated = true;
682                    match quantifier {
683                        Quantifier::Universal => {
684                            if !subformula_value {
685                                result = false;
686                                break;
687                            }
688                        }
689                        Quantifier::Existential => {
690                            if subformula_value {
691                                result = true;
692                                break;
693                            }
694                        }
695                    }
696                }
697                Err(LanguageTypeError::PresuppositionError) => error_found = true,
698                Err(e) => return Err(e),
699                Ok(x) => {
700                    return Err(LanguageTypeError::WrongType {
701                        input: x.to_language_result_type(),
702                        output: LanguageResultType::Bool,
703                    });
704                }
705            }
706        }
707        if error_found && !updated {
708            return Err(LanguageTypeError::PresuppositionError);
709        }
710        self.quantifier_depth -= 1;
711        Ok(LanguageResult::Bool(result))
712    }
713
714    #[allow(clippy::too_many_lines)]
715    fn interp(
716        &mut self,
717        expr: ExprRef,
718        scenario: &Scenario<'a>,
719        variables: &mut VariableBuffer<'a>,
720    ) -> Result<LanguageResult<'a>, LanguageTypeError> {
721        self.check_if_good_to_continue()?;
722        Ok(match self.pool.get(expr) {
723            Expr::Quantifier {
724                quantifier,
725                var_type,
726                restrictor,
727                subformula,
728            } => self.quantification(
729                *quantifier,
730                *var_type,
731                *restrictor,
732                *subformula,
733                scenario,
734                variables,
735            )?,
736            Expr::Variable(i) => variables
737                .get(*i, self.quantifier_depth)
738                .ok_or(LanguageTypeError::MissingVariable(*i))?,
739            Expr::Actor(a) => LanguageResult::Actor(a),
740            Expr::Event(a) => LanguageResult::Event(*a),
741            Expr::Binary(bin_op, lhs, rhs) => {
742                let lhs = self.interp(*lhs, scenario, variables)?;
743                match bin_op {
744                    BinOp::PatientOf | BinOp::AgentOf => {
745                        let a: Actor = lhs.try_into()?;
746                        let rhs = self.interp(*rhs, scenario, variables)?;
747                        let e: Event = rhs.try_into()?;
748                        match bin_op {
749                            BinOp::AgentOf => match scenario.thematic_relations[e as usize].agent {
750                                Some(x) => LanguageResult::Bool(x == a),
751                                None => LanguageResult::Bool(false), //None => return Err(LanguageTypeError::PresuppositionError),
752                            },
753                            BinOp::PatientOf => {
754                                match scenario.thematic_relations[e as usize].patient {
755                                    Some(x) => LanguageResult::Bool(x == a),
756                                    None => LanguageResult::Bool(false), //None => return Err(LanguageTypeError::PresuppositionError),
757                                }
758                            }
759                            _ => panic!("impossible because of previous check"),
760                        }
761                    }
762                    BinOp::Or | BinOp::And => {
763                        let phi: bool = lhs.try_into()?;
764                        LanguageResult::Bool(match bin_op {
765                            BinOp::And => {
766                                if phi {
767                                    let rhs = self.interp(*rhs, scenario, variables)?;
768                                    rhs.try_into()?
769                                } else {
770                                    false
771                                }
772                            }
773                            BinOp::Or => {
774                                if phi {
775                                    true
776                                } else {
777                                    let rhs = self.interp(*rhs, scenario, variables)?;
778                                    rhs.try_into()?
779                                }
780                            }
781                            _ => panic!("impossible because of previous check"),
782                        })
783                    }
784                }
785            }
786            Expr::Constant(constant) => match constant {
787                Constant::Everyone => LanguageResult::ActorSet(scenario.actors.clone()),
788                Constant::EveryEvent => LanguageResult::EventSet(
789                    (0..scenario.thematic_relations.len())
790                        .map(|x| x.try_into().unwrap())
791                        .collect(),
792                ),
793                Constant::Tautology => LanguageResult::Bool(true),
794                Constant::Contradiction => LanguageResult::Bool(false),
795                Constant::Property(p, ActorOrEvent::Actor) => match scenario.properties.get(p) {
796                    Some(property_members) => LanguageResult::ActorSet(
797                        property_members
798                            .iter()
799                            .filter_map(|x| match x {
800                                Entity::Actor(a) => Some(*a),
801                                Entity::Event(_) => None,
802                            })
803                            .collect(),
804                    ),
805                    None => LanguageResult::ActorSet(vec![]),
806                },
807                Constant::Property(p, ActorOrEvent::Event) => match scenario.properties.get(p) {
808                    Some(property_members) => LanguageResult::EventSet(
809                        property_members
810                            .iter()
811                            .filter_map(|x| match x {
812                                Entity::Actor(_) => None,
813                                Entity::Event(e) => Some(*e),
814                            })
815                            .collect(),
816                    ),
817                    None => LanguageResult::EventSet(vec![]),
818                },
819            },
820            Expr::Unary(MonOp::Iota(a_e), arg) => {
821                self.quantifier_depth += 1;
822                let mut variables = variables.clone();
823                let domain: Either<_, _> = match a_e {
824                    ActorOrEvent::Actor => {
825                        Either::Left(scenario.actors.iter().copied().map(Entity::Actor))
826                    }
827                    ActorOrEvent::Event => Either::Right(
828                        (0..scenario.thematic_relations.len())
829                            .map(|x| Entity::Event(x.try_into().unwrap())),
830                    ),
831                };
832                let mut entity = None;
833                for e in domain {
834                    variables.set(self.quantifier_depth - 1, e);
835                    let value: bool = self.interp(*arg, scenario, &mut variables)?.try_into()?;
836                    if value && entity.is_some() {
837                        return Err(LanguageTypeError::PresuppositionError);
838                    } else if value {
839                        entity = Some(e);
840                    }
841                }
842                self.quantifier_depth -= 1;
843                match (entity, a_e) {
844                    (Some(Entity::Actor(a)), ActorOrEvent::Actor) => LanguageResult::Actor(a),
845                    (Some(Entity::Event(e)), ActorOrEvent::Event) => LanguageResult::Event(e),
846                    (None, _) => return Err(LanguageTypeError::PresuppositionError),
847                    _ => panic!("Should be impossible for the variable to not be an actor!"),
848                }
849            }
850
851            Expr::Unary(mon_op, arg) => {
852                let arg = self.interp(*arg, scenario, variables)?;
853                match mon_op {
854                    MonOp::Not => LanguageResult::Bool(!TryInto::<bool>::try_into(arg)?),
855                    MonOp::Property(e, ActorOrEvent::Actor) => {
856                        let arg: Actor = arg.try_into()?;
857                        match scenario.properties.get(e) {
858                            Some(property_members) => {
859                                LanguageResult::Bool(property_members.contains(&Entity::Actor(arg)))
860                            }
861                            None => LanguageResult::Bool(false),
862                        }
863                    }
864                    MonOp::Property(e, ActorOrEvent::Event) => {
865                        let arg: Event = arg.try_into()?;
866                        match scenario.properties.get(e) {
867                            Some(property_members) => {
868                                LanguageResult::Bool(property_members.contains(&Entity::Event(arg)))
869                            }
870                            None => LanguageResult::Bool(false),
871                        }
872                    }
873                    MonOp::Iota(_) => panic!("Captured before!"),
874                }
875            }
876        })
877    }
878}
879
880mod parser;
881pub use parser::LambdaParseError;
882pub use parser::parse_executable;
883use thiserror::Error;
884
885mod lambda_implementation;
886pub use lambda_implementation::ConjoiningError;
887
888#[cfg(feature = "sampling")]
889mod enumerator;
890
891#[cfg(feature = "sampling")]
892mod mutations;
893
894#[cfg(feature = "sampling")]
895pub use mutations::{
896    Context, LambdaEnumerator, LambdaSampler, PossibleExpressions, TypeAgnosticSampler,
897};
898
899mod serializations;
900
901#[cfg(test)]
902mod tests {
903    use crate::ScenarioDataset;
904    use std::collections::BTreeMap;
905
906    use super::*;
907    use crate::ThetaRoles;
908
909    #[test]
910    fn agent_of_and_patient_of() -> anyhow::Result<()> {
911        let simple_scenario = Scenario {
912            question: vec![],
913            actors: vec!["0", "1"],
914            thematic_relations: vec![ThetaRoles {
915                agent: Some("0"),
916                patient: None,
917            }],
918            properties: BTreeMap::default(),
919        };
920
921        let simple_expr = ExprPool(vec![
922            Expr::Actor("0"),
923            Expr::Event(0),
924            Expr::Binary(BinOp::AgentOf, ExprRef(0), ExprRef(1)),
925        ]);
926
927        let expr = LanguageExpression {
928            pool: simple_expr,
929            start: ExprRef(2),
930        };
931        assert_eq!(
932            expr.run(&simple_scenario, None)?,
933            LanguageResult::Bool(true)
934        );
935
936        let simple_expr = ExprPool(vec![
937            Expr::Actor("0"),
938            Expr::Event(0),
939            Expr::Binary(BinOp::PatientOf, ExprRef(0), ExprRef(1)),
940        ]);
941
942        let expr = LanguageExpression {
943            pool: simple_expr,
944            start: ExprRef(2),
945        };
946        assert_eq!(
947            expr.run(&simple_scenario, None).unwrap(),
948            LanguageResult::Bool(false)
949        );
950        Ok(())
951    }
952
953    #[test]
954    fn quantification() -> anyhow::Result<()> {
955        let simple_scenario = Scenario {
956            question: vec![],
957            actors: vec!["0", "1"],
958            thematic_relations: vec![
959                ThetaRoles {
960                    agent: Some("0"),
961                    patient: Some("0"),
962                },
963                ThetaRoles {
964                    agent: Some("1"),
965                    patient: Some("0"),
966                },
967            ],
968            properties: BTreeMap::default(),
969        };
970
971        //For all actors there exists an event such that they are its agent.
972        let simple_expr = ExprPool(vec![
973            Expr::Quantifier {
974                quantifier: Quantifier::Universal,
975                var_type: ActorOrEvent::Actor,
976                restrictor: ExprRef(1),
977                subformula: ExprRef(2),
978            },
979            Expr::Constant(Constant::Everyone),
980            Expr::Quantifier {
981                quantifier: Quantifier::Existential,
982                var_type: ActorOrEvent::Event,
983                restrictor: ExprRef(3),
984                subformula: ExprRef(4),
985            },
986            Expr::Constant(Constant::EveryEvent),
987            Expr::Binary(BinOp::AgentOf, ExprRef(5), ExprRef(6)),
988            Expr::Variable(Variable::Actor(1)),
989            Expr::Variable(Variable::Event(0)),
990        ]);
991
992        let expr = LanguageExpression {
993            pool: simple_expr,
994            start: ExprRef(0),
995        };
996        assert_eq!(
997            expr.run(&simple_scenario, None)?,
998            LanguageResult::Bool(true)
999        );
1000
1001        //For all actors there exists an event such that they are its patient.
1002        let simple_expr = ExprPool(vec![
1003            Expr::Quantifier {
1004                quantifier: Quantifier::Universal,
1005                var_type: ActorOrEvent::Actor,
1006                restrictor: ExprRef(1),
1007                subformula: ExprRef(2),
1008            },
1009            Expr::Constant(Constant::Everyone),
1010            Expr::Quantifier {
1011                quantifier: Quantifier::Existential,
1012                var_type: ActorOrEvent::Event,
1013                restrictor: ExprRef(3),
1014                subformula: ExprRef(4),
1015            },
1016            Expr::Constant(Constant::EveryEvent),
1017            Expr::Binary(BinOp::PatientOf, ExprRef(5), ExprRef(6)),
1018            Expr::Variable(Variable::Actor(1)),
1019            Expr::Variable(Variable::Event(0)),
1020        ]);
1021        let expr = LanguageExpression {
1022            pool: simple_expr,
1023            start: ExprRef(0),
1024        };
1025        assert_eq!(
1026            expr.run(&simple_scenario, None)?,
1027            LanguageResult::Bool(false)
1028        );
1029        Ok(())
1030    }
1031
1032    #[test]
1033    fn logic() -> anyhow::Result<()> {
1034        let simple_scenario = Scenario {
1035            question: vec![],
1036            actors: vec!["0", "1"],
1037            thematic_relations: vec![
1038                ThetaRoles {
1039                    agent: Some("0"),
1040                    patient: Some("0"),
1041                },
1042                ThetaRoles {
1043                    agent: Some("1"),
1044                    patient: Some("0"),
1045                },
1046            ],
1047            properties: BTreeMap::default(),
1048        };
1049
1050        assert_eq!(
1051            LanguageExpression {
1052                pool: ExprPool(vec![Expr::Constant(Constant::Contradiction)]),
1053                start: ExprRef(0)
1054            }
1055            .run(&simple_scenario, None)?,
1056            LanguageResult::Bool(false)
1057        );
1058
1059        assert_eq!(
1060            LanguageExpression {
1061                pool: ExprPool(vec![Expr::Constant(Constant::Tautology)]),
1062                start: ExprRef(0)
1063            }
1064            .run(&simple_scenario, None)?,
1065            LanguageResult::Bool(true)
1066        );
1067
1068        //\neg \bot
1069        let simple_expr = ExprPool(vec![
1070            Expr::Unary(MonOp::Not, ExprRef(1)),
1071            Expr::Constant(Constant::Contradiction),
1072        ]);
1073        let expr = LanguageExpression {
1074            pool: simple_expr,
1075            start: ExprRef(0),
1076        };
1077        assert_eq!(
1078            expr.run(&simple_scenario, None)?,
1079            LanguageResult::Bool(true)
1080        );
1081
1082        //\neg \top
1083        let simple_expr = ExprPool(vec![
1084            Expr::Unary(MonOp::Not, ExprRef(1)),
1085            Expr::Constant(Constant::Tautology),
1086        ]);
1087        let expr = LanguageExpression {
1088            pool: simple_expr,
1089            start: ExprRef(0),
1090        };
1091        assert_eq!(
1092            expr.run(&simple_scenario, None)?,
1093            LanguageResult::Bool(false)
1094        );
1095
1096        //(\neg \bot) \lor (\bot)
1097        let simple_expr = ExprPool(vec![
1098            Expr::Binary(BinOp::Or, ExprRef(1), ExprRef(3)),
1099            Expr::Unary(MonOp::Not, ExprRef(2)),
1100            Expr::Constant(Constant::Contradiction),
1101            Expr::Constant(Constant::Contradiction),
1102        ]);
1103        let expr = LanguageExpression {
1104            pool: simple_expr,
1105            start: ExprRef(0),
1106        };
1107        assert_eq!(
1108            expr.run(&simple_scenario, None)?,
1109            LanguageResult::Bool(true)
1110        );
1111
1112        //(\neg \bot) \and (\bot)
1113        let simple_expr = ExprPool(vec![
1114            Expr::Binary(BinOp::And, ExprRef(1), ExprRef(3)),
1115            Expr::Unary(MonOp::Not, ExprRef(2)),
1116            Expr::Constant(Constant::Contradiction),
1117            Expr::Constant(Constant::Contradiction),
1118        ]);
1119        let expr = LanguageExpression {
1120            pool: simple_expr,
1121            start: ExprRef(0),
1122        };
1123        assert_eq!(
1124            expr.run(&simple_scenario, None)?,
1125            LanguageResult::Bool(false)
1126        );
1127
1128        //For all actors there exists an event such that they are its patient and TOP.
1129        let simple_expr = ExprPool(vec![
1130            Expr::Quantifier {
1131                quantifier: Quantifier::Universal,
1132                var_type: ActorOrEvent::Actor,
1133                restrictor: ExprRef(1),
1134                subformula: ExprRef(2),
1135            },
1136            Expr::Constant(Constant::Everyone),
1137            Expr::Quantifier {
1138                quantifier: Quantifier::Existential,
1139                var_type: ActorOrEvent::Event,
1140                restrictor: ExprRef(3),
1141                subformula: ExprRef(4),
1142            },
1143            Expr::Constant(Constant::EveryEvent),
1144            Expr::Binary(BinOp::And, ExprRef(5), ExprRef(8)),
1145            Expr::Binary(BinOp::PatientOf, ExprRef(6), ExprRef(7)),
1146            Expr::Variable(Variable::Actor(1)),
1147            Expr::Variable(Variable::Event(0)),
1148            Expr::Constant(Constant::Tautology),
1149        ]);
1150        let expr = LanguageExpression {
1151            pool: simple_expr,
1152            start: ExprRef(0),
1153        };
1154        assert_eq!(
1155            expr.run(&simple_scenario, None)?,
1156            LanguageResult::Bool(false)
1157        );
1158        Ok(())
1159    }
1160
1161    #[test]
1162    fn properties() -> anyhow::Result<()> {
1163        let mut properties = BTreeMap::default();
1164        properties.insert("1", vec![Entity::Actor("0"), Entity::Actor("1")]);
1165        properties.insert("534", vec![Entity::Actor("1")]);
1166        let simple_scenario = Scenario {
1167            question: vec![],
1168            actors: vec!["0", "1"],
1169            thematic_relations: vec![
1170                ThetaRoles {
1171                    agent: Some("0"),
1172                    patient: Some("0"),
1173                },
1174                ThetaRoles {
1175                    agent: Some("1"),
1176                    patient: Some("0"),
1177                },
1178            ],
1179            properties,
1180        };
1181
1182        // everyone is of property type one.
1183        let simple_expr = ExprPool(vec![
1184            Expr::Quantifier {
1185                quantifier: Quantifier::Universal,
1186                var_type: ActorOrEvent::Actor,
1187                restrictor: ExprRef(1),
1188                subformula: ExprRef(2),
1189            },
1190            Expr::Constant(Constant::Everyone),
1191            Expr::Unary(MonOp::Property("1", ActorOrEvent::Actor), ExprRef(3)),
1192            Expr::Variable(Variable::Actor(0)),
1193        ]);
1194        let expr = LanguageExpression {
1195            pool: simple_expr,
1196            start: ExprRef(0),
1197        };
1198        assert_eq!(
1199            expr.run(&simple_scenario, None)?,
1200            LanguageResult::Bool(true)
1201        );
1202        // someone is of property type 534.
1203        let simple_expr = ExprPool(vec![
1204            Expr::Quantifier {
1205                quantifier: Quantifier::Existential,
1206                var_type: ActorOrEvent::Actor,
1207                restrictor: ExprRef(1),
1208                subformula: ExprRef(2),
1209            },
1210            Expr::Constant(Constant::Everyone),
1211            Expr::Unary(MonOp::Property("534", ActorOrEvent::Actor), ExprRef(3)),
1212            Expr::Variable(Variable::Actor(0)),
1213        ]);
1214        let expr = LanguageExpression {
1215            pool: simple_expr,
1216            start: ExprRef(0),
1217        };
1218        assert_eq!(
1219            expr.run(&simple_scenario, None)?,
1220            LanguageResult::Bool(true)
1221        );
1222        Ok(())
1223    }
1224
1225    #[test]
1226    fn complicated_restrictors() -> anyhow::Result<()> {
1227        let mut properties = BTreeMap::default();
1228        properties.insert("534", vec![Entity::Actor("1")]);
1229        properties.insert("235", vec![Entity::Event(0)]);
1230        properties.insert("2", vec![Entity::Actor("0")]);
1231        let simple_scenario = Scenario {
1232            question: vec![],
1233            actors: vec!["0", "1"],
1234            thematic_relations: vec![ThetaRoles {
1235                agent: Some("1"),
1236                patient: Some("0"),
1237            }],
1238            properties,
1239        };
1240
1241        // all property type 534 objects are agents of a 235-event
1242        let simple_expr = ExprPool(vec![
1243            Expr::Quantifier {
1244                quantifier: Quantifier::Universal,
1245                var_type: ActorOrEvent::Actor,
1246                restrictor: ExprRef(1),
1247                subformula: ExprRef(2),
1248            },
1249            Expr::Constant(Constant::Property("534", ActorOrEvent::Actor)),
1250            Expr::Quantifier {
1251                quantifier: Quantifier::Existential,
1252                var_type: ActorOrEvent::Event,
1253                restrictor: ExprRef(3),
1254                subformula: ExprRef(4),
1255            },
1256            Expr::Constant(Constant::Property("235", ActorOrEvent::Event)),
1257            Expr::Binary(BinOp::AgentOf, ExprRef(5), ExprRef(6)),
1258            Expr::Variable(Variable::Actor(1)),
1259            Expr::Variable(Variable::Event(0)),
1260        ]);
1261
1262        let expr = LanguageExpression {
1263            pool: simple_expr,
1264            start: ExprRef(0),
1265        };
1266        assert_eq!(
1267            expr.run(&simple_scenario, None)?,
1268            LanguageResult::Bool(true)
1269        );
1270        // all property type 2 objects are agents of a 235-event (which is false)
1271        let simple_expr = ExprPool(vec![
1272            Expr::Quantifier {
1273                quantifier: Quantifier::Universal,
1274                var_type: ActorOrEvent::Actor,
1275                restrictor: ExprRef(1),
1276                subformula: ExprRef(2),
1277            },
1278            Expr::Constant(Constant::Property("2", ActorOrEvent::Actor)),
1279            Expr::Quantifier {
1280                quantifier: Quantifier::Existential,
1281                var_type: ActorOrEvent::Event,
1282                restrictor: ExprRef(3),
1283                subformula: ExprRef(4),
1284            },
1285            Expr::Constant(Constant::Property("235", ActorOrEvent::Event)),
1286            Expr::Binary(BinOp::AgentOf, ExprRef(5), ExprRef(6)),
1287            Expr::Variable(Variable::Actor(1)),
1288            Expr::Variable(Variable::Event(0)),
1289        ]);
1290        let expr = LanguageExpression {
1291            pool: simple_expr,
1292            start: ExprRef(0),
1293        };
1294        assert_eq!(
1295            expr.run(&simple_scenario, None)?,
1296            LanguageResult::Bool(false)
1297        );
1298
1299        let mut properties = BTreeMap::default();
1300        properties.insert("3", vec![Entity::Actor("1"), Entity::Actor("2")]);
1301        properties.insert("2", vec![Entity::Actor("1"), Entity::Actor("3")]);
1302        properties.insert("4", vec![Entity::Event(0)]);
1303        let simple_scenario = Scenario {
1304            question: vec![],
1305            actors: vec!["0", "1", "2", "3", "4"],
1306            thematic_relations: vec![ThetaRoles {
1307                agent: Some("1"),
1308                patient: Some("0"),
1309            }],
1310            properties,
1311        };
1312        //All property type 2 and property type 3 actors are an agent of an event
1313        let simple_expr = ExprPool(vec![
1314            Expr::Quantifier {
1315                quantifier: Quantifier::Universal,
1316                var_type: ActorOrEvent::Actor,
1317                restrictor: ExprRef(1),
1318                subformula: ExprRef(6),
1319            },
1320            Expr::Binary(BinOp::And, ExprRef(2), ExprRef(4)),
1321            Expr::Unary(MonOp::Property("2", ActorOrEvent::Actor), ExprRef(3)),
1322            Expr::Variable(Variable::Actor(0)),
1323            Expr::Unary(MonOp::Property("3", ActorOrEvent::Actor), ExprRef(5)),
1324            Expr::Variable(Variable::Actor(0)), //5
1325            Expr::Quantifier {
1326                quantifier: Quantifier::Existential,
1327                var_type: ActorOrEvent::Actor,
1328                restrictor: ExprRef(7),
1329                subformula: ExprRef(8),
1330            },
1331            Expr::Constant(Constant::EveryEvent),
1332            Expr::Binary(BinOp::AgentOf, ExprRef(9), ExprRef(10)),
1333            Expr::Variable(Variable::Actor(1)),
1334            Expr::Variable(Variable::Event(0)),
1335        ]);
1336        let expr = LanguageExpression {
1337            pool: simple_expr,
1338            start: ExprRef(0),
1339        };
1340        assert_eq!(
1341            expr.run(&simple_scenario, None)?,
1342            LanguageResult::Bool(true)
1343        );
1344        //All property type 2 and property type 3 actors are patients of an event
1345        let simple_expr = ExprPool(vec![
1346            Expr::Quantifier {
1347                quantifier: Quantifier::Universal,
1348                var_type: ActorOrEvent::Actor,
1349                restrictor: ExprRef(1),
1350                subformula: ExprRef(6),
1351            },
1352            Expr::Binary(BinOp::And, ExprRef(2), ExprRef(4)),
1353            Expr::Unary(MonOp::Property("2", ActorOrEvent::Actor), ExprRef(3)),
1354            Expr::Variable(Variable::Actor(0)),
1355            Expr::Unary(MonOp::Property("3", ActorOrEvent::Actor), ExprRef(5)),
1356            Expr::Variable(Variable::Actor(0)), //5
1357            Expr::Quantifier {
1358                quantifier: Quantifier::Existential,
1359                var_type: ActorOrEvent::Event,
1360                restrictor: ExprRef(7),
1361                subformula: ExprRef(8),
1362            },
1363            Expr::Constant(Constant::EveryEvent),
1364            Expr::Binary(BinOp::PatientOf, ExprRef(9), ExprRef(10)),
1365            Expr::Variable(Variable::Actor(1)),
1366            Expr::Variable(Variable::Event(0)),
1367        ]);
1368        let expr = LanguageExpression {
1369            pool: simple_expr,
1370            start: ExprRef(0),
1371        };
1372        assert_eq!(
1373            expr.run(&simple_scenario, None)?,
1374            LanguageResult::Bool(false)
1375        );
1376        Ok(())
1377    }
1378
1379    #[test]
1380    fn error_handling() -> anyhow::Result<()> {
1381        let expr = parse_executable("some_e(y,pe_1,PatientOf(a_1,y))")?;
1382
1383        let a = Scenario {
1384            question: vec![],
1385            actors: vec!["1", "0"],
1386            thematic_relations: vec![ThetaRoles {
1387                agent: Some("0"),
1388                patient: Some("1"),
1389            }],
1390            properties: vec![("1", vec![Entity::Event(0)])].into_iter().collect(),
1391        };
1392
1393        let b = Scenario {
1394            question: vec![],
1395            actors: vec!["1"],
1396            thematic_relations: vec![ThetaRoles {
1397                agent: Some("1"),
1398                patient: None,
1399            }],
1400            properties: vec![("0", vec![Entity::Event(0)])].into_iter().collect(),
1401        };
1402        assert_eq!(
1403            expr.run(&b, None),
1404            Err(LanguageTypeError::PresuppositionError)
1405        );
1406        expr.run(&a, None)?;
1407
1408        Ok(())
1409    }
1410
1411    #[test]
1412    fn weird_and_not_behaviour() -> anyhow::Result<()> {
1413        let scenario = "\"Phil danced\" <John (man), Mary (woman), Susan (woman), Phil (man); {A: Phil (dance)}, {A: Mary (run)}>";
1414
1415        let labels = ScenarioDataset::parse(scenario)?;
1416
1417        let a = LanguageExpression::parse("every_e(x,pe_dance,AgentOf(a_Phil,x))")?;
1418        let b = LanguageExpression::parse("every_e(x,pe_dance,AgentOf(a_Mary,x))")?;
1419        let c = LanguageExpression::parse(
1420            "(every_e(x,pe_dance,AgentOf(a_Phil,x)))&~(every_e(x,pe_dance,AgentOf(a_Mary,x)))",
1421        )?;
1422        let scenario = labels.iter_scenarios().next().unwrap();
1423        assert_eq!(a.run(scenario, None)?, LanguageResult::Bool(true));
1424        assert_eq!(b.run(scenario, None)?, LanguageResult::Bool(false));
1425        assert_eq!(c.run(scenario, None)?, LanguageResult::Bool(true));
1426
1427        let pool = LanguageExpression::parse(
1428            "every_e(x, AgentOf(a_Mary, x), PatientOf(a_Phil, x)) & ~every_e(x, AgentOf(a_John, x), PatientOf(a_Phil, x)) & ~every_e(x, AgentOf(a_Phil, x), PatientOf(a_Phil, x)) & ~every_e(x, AgentOf(a_Sue, x), PatientOf(a_Phil, x))",
1429        )?;
1430        let labels = ScenarioDataset::parse(
1431            "\"Mary loves Phil\" <John (man), Mary (woman), Phil (man), Sue (woman); {A: Mary, P: Phil (loves)}> lambda a x some_e(e, pe_loves, AgentOf(x, e)); lambda a x some_e(e, pe_loves, PatientOf(x, e)); lambda <a,<a,t>> P P(a_Phil, a_Mary) & ~P(a_John, a_Mary) & ~P(a_Mary, a_Mary) & ~P(a_Sue, a_Mary); lambda <a,t> P P(a_Mary) & ~P(a_John) & ~P(a_Phil) & ~P(a_Sue)",
1432        )?;
1433
1434        let config = ExecutionConfig::default().allow_empty_quantification();
1435        let scenario = labels.iter_scenarios().next().unwrap();
1436
1437        pool.run(scenario, Some(config))?;
1438
1439        let pool = LanguageExpression::parse(
1440            "some_e(x, all_e, AgentOf(a_John, x) & PatientOf(a_Mary, x) & pe_helps(x))",
1441        )?;
1442        let labels = ScenarioDataset::parse(
1443            "\"John helps Mary\" <John (man), Phil (man), Mary (woman); {A: John (sleeps)}, {A: John, P: Mary (helps)}> lambda a x AgentOf(x, e_1); lambda <a, t> P P(a_John) & ~P(a_Phil) & ~P(a_Mary); lambda a x PatientOf(x, e_1); lambda <a, <a, t>> P P(a_Mary, a_John) & ~P(a_John, a_John) & ~P(a_Phil, a_John)",
1444        )?;
1445
1446        let config = ExecutionConfig::default().allow_empty_quantification();
1447        let scenario = labels.iter_scenarios().next().unwrap();
1448
1449        assert_eq!(
1450            pool.run(scenario, Some(config))?,
1451            LanguageResult::Bool(true)
1452        );
1453
1454        Ok(())
1455    }
1456
1457    #[test]
1458    fn iota_tests() -> anyhow::Result<()> {
1459        let scenario = "\"The man danced\" <John (man), Mary (woman), Susan (woman); {A: John (dance)}, {A: Mary (run)}>";
1460
1461        let labels = ScenarioDataset::parse(scenario)?;
1462
1463        let a = LanguageExpression::parse("every_e(x,pe_dance,AgentOf(iota(x, pa_man(x)),x))")?;
1464        let b = LanguageExpression::parse("every_e(x,pe_dance,AgentOf(iota(x, pa_woman(x)),x))")?;
1465        let c = LanguageExpression::parse("every_e(x,pe_dance,AgentOf(iota(x, pa_red(x)),x))")?;
1466
1467        let d = LanguageExpression::parse("iota_e(x, pe_dance(x))")?;
1468        let scenario = labels.iter_scenarios().next().unwrap();
1469        assert_eq!(
1470            a.to_string(),
1471            "every_e(x, pe_dance, AgentOf(iota(y, pa_man(y)), x))"
1472        );
1473        assert_eq!(a.run(scenario, None)?, LanguageResult::Bool(true));
1474        assert_eq!(
1475            b.run(scenario, None),
1476            Err(LanguageTypeError::PresuppositionError)
1477        );
1478        assert_eq!(
1479            c.run(scenario, None),
1480            Err(LanguageTypeError::PresuppositionError)
1481        );
1482        assert_eq!(d.run(scenario, None), Ok(LanguageResult::Event(0)));
1483
1484        Ok(())
1485    }
1486}