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    pub fn run(
294        &self,
295        scenario: &Scenario<'a>,
296        config: Option<ExecutionConfig>,
297    ) -> Result<LanguageResult<'a>, LanguageTypeError> {
298        let mut variables = VariableBuffer::default();
299        Execution {
300            pool: &self.pool,
301            n_steps: 0,
302
303            #[cfg(not(target_arch = "wasm32"))]
304            start: Instant::now(),
305
306            config: &config.unwrap_or_default(),
307            quantifier_depth: 0,
308        }
309        .interp(self.start, scenario, &mut variables)
310    }
311
312    ///Parse a given language of thought expression and return the [`LanguageExpression`]. This
313    ///does not support tools from the lambda calculus, see [`RootedLambdaPool`].
314    pub fn parse(s: &'a str) -> Result<LanguageExpression<'a>, LambdaParseError> {
315        Ok(RootedLambdaPool::parse(s)?.into_pool()?)
316    }
317
318    #[allow(dead_code)]
319    ///Create a `LanguageExpression` out of a [`ExprRef`] and a [`ExprPool`]
320    pub(crate) fn new(pool: ExprPool<'a>, start: ExprRef) -> Self {
321        LanguageExpression { pool, start }
322    }
323}
324
325struct Execution<'a, 'b> {
326    pool: &'b ExprPool<'a>,
327    n_steps: usize,
328    #[cfg(not(target_arch = "wasm32"))]
329    start: Instant,
330    config: &'b ExecutionConfig,
331
332    quantifier_depth: usize,
333}
334
335impl Execution<'_, '_> {
336    fn check_if_good_to_continue(&mut self) -> Result<(), LanguageTypeError> {
337        if let Some(max_steps) = self.config.max_steps
338            && self.n_steps > max_steps
339        {
340            return Err(LanguageTypeError::TooManySteps(max_steps));
341        }
342
343        #[cfg(not(target_arch = "wasm32"))]
344        if let Some(max_time) = self.config.timeout
345            && self.start.elapsed() > max_time
346        {
347            return Err(LanguageTypeError::TimeOut);
348        }
349
350        self.n_steps += 1;
351        Ok(())
352    }
353}
354
355#[derive(Debug, Clone, PartialEq, Eq, Default, Hash)]
356struct VariableBuffer<'a>(Vec<Option<Entity<'a>>>);
357
358impl<'a> VariableBuffer<'a> {
359    fn set(&mut self, i: usize, x: Entity<'a>) {
360        if self.0.len() <= i {
361            self.0.resize(i + 1, None);
362        }
363        self.0[i] = Some(x);
364    }
365
366    fn get(&self, v: Variable, quantifier_depth: usize) -> Option<LanguageResult<'a>> {
367        let pos = (quantifier_depth).checked_sub(v.id() as usize + 1)?;
368        match self.0.get(pos) {
369            Some(x) => match (v, x) {
370                (Variable::Actor(_), Some(Entity::Actor(a))) => Some(LanguageResult::Actor(a)),
371                (Variable::Event(_), Some(Entity::Event(e))) => Some(LanguageResult::Event(*e)),
372                _ => None,
373            },
374            None => None,
375        }
376    }
377}
378
379///The result of running a [`LanguageExpression`], see [`LanguageExpression::run`].
380#[derive(Debug, Clone, PartialEq, Eq, Hash)]
381#[allow(missing_docs)]
382pub enum LanguageResult<'a> {
383    Bool(bool),
384    Actor(Actor<'a>),
385    Event(Event),
386    ///A set of actors (represented as a vector).
387    ActorSet(Vec<Actor<'a>>),
388    ///A set of events (represented as a vector).
389    EventSet(Vec<Event>),
390}
391
392impl LanguageResult<'_> {
393    fn to_language_result_type(&self) -> LanguageResultType {
394        match self {
395            LanguageResult::Bool(_) => LanguageResultType::Bool,
396            LanguageResult::Actor(_) => LanguageResultType::Actor,
397            LanguageResult::Event(_) => LanguageResultType::Event,
398            LanguageResult::ActorSet(_) => LanguageResultType::ActorSet,
399            LanguageResult::EventSet(_) => LanguageResultType::EventSet,
400        }
401    }
402}
403
404impl Display for LanguageResult<'_> {
405    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
406        match self {
407            LanguageResult::Bool(b) => write!(f, "{b}"),
408            LanguageResult::Actor(a) => write!(f, "a_{a}"),
409            LanguageResult::Event(e) => write!(f, "e_{e}"),
410            LanguageResult::ActorSet(items) => {
411                write!(
412                    f,
413                    "{{{}}}",
414                    items
415                        .iter()
416                        .map(|x| format!("a_{x}"))
417                        .collect::<Vec<_>>()
418                        .join(", ")
419                )
420            }
421            LanguageResult::EventSet(items) => write!(
422                f,
423                "{{{}}}",
424                items
425                    .iter()
426                    .map(|x| format!("e{x}"))
427                    .collect::<Vec<_>>()
428                    .join(", ")
429            ),
430        }
431    }
432}
433
434///The basic atomic types of the LOT. See [`LanguageResult`].
435#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
436#[allow(missing_docs)]
437pub enum LanguageResultType {
438    Bool,
439    Actor,
440    ActorSet,
441    Event,
442    EventSet,
443}
444
445impl Display for LanguageResultType {
446    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
447        write!(
448            f,
449            "{}",
450            match self {
451                LanguageResultType::Bool => "t",
452                LanguageResultType::Actor => "a",
453                LanguageResultType::ActorSet => "<a,t>",
454                LanguageResultType::Event => "e",
455                LanguageResultType::EventSet => "<e,t>",
456            }
457        )
458    }
459}
460
461///Possible errors that can be generated when running a [`LanguageExpression`]
462#[derive(Error, Debug, Copy, Clone, PartialEq, Eq)]
463pub enum LanguageTypeError {
464    ///A presupposition error in the semantics; occurs when a non-existent entity is referenced.
465    #[error("The referenced object does not exist in the current scenario")]
466    PresuppositionError,
467
468    ///A variable that is not bound that was used.
469    #[error("The referenced variable ({0:?}) does not exist in the current scenario")]
470    MissingVariable(Variable),
471
472    ///A type conversion which is violated.
473    #[error("Can't convert from {input} to {output}")]
474    WrongType {
475        ///The input type of the conversion
476        input: LanguageResultType,
477        ///The output type of the conversion
478        output: LanguageResultType,
479    },
480
481    ///The execution ran out of steps
482    #[error("The execution took more than {0} steps")]
483    TooManySteps(usize),
484
485    ///The execution ran out of time (unavailable on wasm).
486    #[error("The execution ran out of time")]
487    TimeOut,
488}
489
490impl TryFrom<LanguageResult<'_>> for Event {
491    type Error = LanguageTypeError;
492
493    fn try_from(value: LanguageResult) -> Result<Self, Self::Error> {
494        match value {
495            LanguageResult::Event(x) => Ok(x),
496            _ => Err(LanguageTypeError::WrongType {
497                input: value.to_language_result_type(),
498                output: LanguageResultType::Event,
499            }),
500        }
501    }
502}
503
504impl<'a> TryFrom<LanguageResult<'a>> for Actor<'a> {
505    type Error = LanguageTypeError;
506
507    fn try_from(value: LanguageResult<'a>) -> Result<Self, Self::Error> {
508        match value {
509            LanguageResult::Actor(x) => Ok(x),
510            _ => Err(LanguageTypeError::WrongType {
511                input: value.to_language_result_type(),
512                output: LanguageResultType::Actor,
513            }),
514        }
515    }
516}
517
518impl TryFrom<LanguageResult<'_>> for bool {
519    type Error = LanguageTypeError;
520
521    fn try_from(value: LanguageResult) -> Result<Self, Self::Error> {
522        match value {
523            LanguageResult::Bool(x) => Ok(x),
524            _ => Err(LanguageTypeError::WrongType {
525                input: value.to_language_result_type(),
526                output: LanguageResultType::Bool,
527            }),
528        }
529    }
530}
531
532impl<'a> TryFrom<LanguageResult<'a>> for Vec<Actor<'a>> {
533    type Error = LanguageTypeError;
534
535    fn try_from(value: LanguageResult<'a>) -> Result<Self, Self::Error> {
536        match value {
537            LanguageResult::ActorSet(x) => Ok(x),
538            _ => Err(LanguageTypeError::WrongType {
539                input: value.to_language_result_type(),
540                output: LanguageResultType::ActorSet,
541            }),
542        }
543    }
544}
545
546impl TryFrom<LanguageResult<'_>> for Vec<Event> {
547    type Error = LanguageTypeError;
548
549    fn try_from(value: LanguageResult) -> Result<Self, Self::Error> {
550        match value {
551            LanguageResult::EventSet(x) => Ok(x),
552            _ => Err(LanguageTypeError::WrongType {
553                input: value.to_language_result_type(),
554                output: LanguageResultType::EventSet,
555            }),
556        }
557    }
558}
559
560impl<'a> From<Vec<Expr<'a>>> for ExprPool<'a> {
561    fn from(value: Vec<Expr<'a>>) -> Self {
562        ExprPool(value)
563    }
564}
565
566impl<'a> ExprPool<'a> {
567    fn get(&self, expr: ExprRef) -> &Expr<'a> {
568        &self.0[expr.0 as usize]
569    }
570
571    fn get_type(&self, expr: ExprRef) -> LanguageResultType {
572        match self.get(expr) {
573            Expr::Variable(Variable::Actor(_)) | Expr::Actor(_) => LanguageResultType::Actor,
574            Expr::Variable(Variable::Event(_)) | Expr::Event(_) => LanguageResultType::Event,
575            Expr::Quantifier { .. } | Expr::Binary(..) | Expr::Unary(..) => {
576                LanguageResultType::Bool
577            }
578            Expr::Constant(constant) => match constant {
579                Constant::Everyone | Constant::Property(_, ActorOrEvent::Actor) => {
580                    LanguageResultType::ActorSet
581                }
582                Constant::EveryEvent | Constant::Property(_, ActorOrEvent::Event) => {
583                    LanguageResultType::EventSet
584                }
585                Constant::Tautology | Constant::Contradiction => LanguageResultType::Bool,
586            },
587        }
588    }
589}
590
591impl<'a> Execution<'a, '_> {
592    fn quantification(
593        &mut self,
594        quantifier: Quantifier,
595        var_type: ActorOrEvent,
596        restrictor: ExprRef,
597        subformula: ExprRef,
598        scenario: &Scenario<'a>,
599        variables: &mut VariableBuffer<'a>,
600    ) -> Result<LanguageResult<'a>, LanguageTypeError> {
601        self.quantifier_depth += 1;
602        let mut variables = variables.clone();
603        let domain: Vec<Entity> = match self.pool.get_type(restrictor) {
604            LanguageResultType::Bool => {
605                let mut domain = vec![];
606                match var_type {
607                    ActorOrEvent::Actor => {
608                        for e in &scenario.actors {
609                            variables.set(self.quantifier_depth - 1, Entity::Actor(e));
610                            let truth_value_for_e: bool = self
611                                .interp(restrictor, scenario, &mut variables)?
612                                .try_into()?;
613                            if truth_value_for_e {
614                                domain.push(Entity::Actor(e));
615                            }
616                        }
617                    }
618                    ActorOrEvent::Event => {
619                        for e in scenario.events() {
620                            variables.set(self.quantifier_depth - 1, Entity::Event(e));
621                            let truth_value_for_e: bool = self
622                                .interp(restrictor, scenario, &mut variables)?
623                                .try_into()?;
624                            if truth_value_for_e {
625                                domain.push(Entity::Event(e));
626                            }
627                        }
628                    }
629                }
630                domain
631            }
632            LanguageResultType::Actor => {
633                let e: Actor = self
634                    .interp(restrictor, scenario, &mut variables)?
635                    .try_into()?;
636                vec![Entity::Actor(e)]
637            }
638            LanguageResultType::ActorSet => {
639                let a: Vec<Actor> = self
640                    .interp(restrictor, scenario, &mut variables)?
641                    .try_into()?;
642                a.into_iter().map(Entity::Actor).collect()
643            }
644            LanguageResultType::Event => {
645                let e: Event = self
646                    .interp(restrictor, scenario, &mut variables)?
647                    .try_into()?;
648                vec![Entity::Event(e)]
649            }
650            LanguageResultType::EventSet => {
651                let a: Vec<Event> = self
652                    .interp(restrictor, scenario, &mut variables)?
653                    .try_into()?;
654                a.into_iter().map(Entity::Event).collect()
655            }
656        };
657
658        if !self.config.empty_quantification && domain.is_empty() {
659            return Err(LanguageTypeError::PresuppositionError);
660        }
661
662        let mut result = match quantifier {
663            Quantifier::Universal => true,
664            Quantifier::Existential => false,
665        };
666        let mut updated = false;
667        let mut error_found = false;
668        for e in domain {
669            variables.set(self.quantifier_depth - 1, e);
670            match self.interp(subformula, scenario, &mut variables) {
671                Ok(LanguageResult::Bool(subformula_value)) => {
672                    updated = true;
673                    match quantifier {
674                        Quantifier::Universal => {
675                            if !subformula_value {
676                                result = false;
677                                break;
678                            }
679                        }
680                        Quantifier::Existential => {
681                            if subformula_value {
682                                result = true;
683                                break;
684                            }
685                        }
686                    }
687                }
688                Err(LanguageTypeError::PresuppositionError) => error_found = true,
689                Err(e) => return Err(e),
690                Ok(x) => {
691                    return Err(LanguageTypeError::WrongType {
692                        input: x.to_language_result_type(),
693                        output: LanguageResultType::Bool,
694                    });
695                }
696            }
697        }
698        if error_found && !updated {
699            return Err(LanguageTypeError::PresuppositionError);
700        }
701        self.quantifier_depth -= 1;
702        Ok(LanguageResult::Bool(result))
703    }
704
705    fn interp(
706        &mut self,
707        expr: ExprRef,
708        scenario: &Scenario<'a>,
709        variables: &mut VariableBuffer<'a>,
710    ) -> Result<LanguageResult<'a>, LanguageTypeError> {
711        self.check_if_good_to_continue()?;
712        Ok(match self.pool.get(expr) {
713            Expr::Quantifier {
714                quantifier,
715                var_type,
716                restrictor,
717                subformula,
718            } => self.quantification(
719                *quantifier,
720                *var_type,
721                *restrictor,
722                *subformula,
723                scenario,
724                variables,
725            )?,
726            Expr::Variable(i) => variables
727                .get(*i, self.quantifier_depth)
728                .ok_or(LanguageTypeError::MissingVariable(*i))?,
729            Expr::Actor(a) => LanguageResult::Actor(a),
730            Expr::Event(a) => LanguageResult::Event(*a),
731            Expr::Binary(bin_op, lhs, rhs) => {
732                let lhs = self.interp(*lhs, scenario, variables)?;
733                match bin_op {
734                    BinOp::PatientOf | BinOp::AgentOf => {
735                        let a: Actor = lhs.try_into()?;
736                        let rhs = self.interp(*rhs, scenario, variables)?;
737                        let e: Event = rhs.try_into()?;
738                        match bin_op {
739                            BinOp::AgentOf => match scenario.thematic_relations[e as usize].agent {
740                                Some(x) => LanguageResult::Bool(x == a),
741                                None => LanguageResult::Bool(false), //None => return Err(LanguageTypeError::PresuppositionError),
742                            },
743                            BinOp::PatientOf => {
744                                match scenario.thematic_relations[e as usize].patient {
745                                    Some(x) => LanguageResult::Bool(x == a),
746                                    None => LanguageResult::Bool(false), //None => return Err(LanguageTypeError::PresuppositionError),
747                                }
748                            }
749                            _ => panic!("impossible because of previous check"),
750                        }
751                    }
752                    BinOp::Or | BinOp::And => {
753                        let phi: bool = lhs.try_into()?;
754                        LanguageResult::Bool(match bin_op {
755                            BinOp::And => {
756                                if phi {
757                                    let rhs = self.interp(*rhs, scenario, variables)?;
758                                    rhs.try_into()?
759                                } else {
760                                    false
761                                }
762                            }
763                            BinOp::Or => {
764                                if phi {
765                                    true
766                                } else {
767                                    let rhs = self.interp(*rhs, scenario, variables)?;
768                                    rhs.try_into()?
769                                }
770                            }
771                            _ => panic!("impossible because of previous check"),
772                        })
773                    }
774                }
775            }
776            Expr::Constant(constant) => match constant {
777                Constant::Everyone => LanguageResult::ActorSet(scenario.actors.clone()),
778                Constant::EveryEvent => LanguageResult::EventSet(
779                    (0..scenario.thematic_relations.len())
780                        .map(|x| x.try_into().unwrap())
781                        .collect(),
782                ),
783                Constant::Tautology => LanguageResult::Bool(true),
784                Constant::Contradiction => LanguageResult::Bool(false),
785                Constant::Property(p, ActorOrEvent::Actor) => match scenario.properties.get(p) {
786                    Some(property_members) => LanguageResult::ActorSet(
787                        property_members
788                            .iter()
789                            .filter_map(|x| match x {
790                                Entity::Actor(a) => Some(*a),
791                                Entity::Event(_) => None,
792                            })
793                            .collect(),
794                    ),
795                    None => LanguageResult::ActorSet(vec![]),
796                },
797                Constant::Property(p, ActorOrEvent::Event) => match scenario.properties.get(p) {
798                    Some(property_members) => LanguageResult::EventSet(
799                        property_members
800                            .iter()
801                            .filter_map(|x| match x {
802                                Entity::Actor(_) => None,
803                                Entity::Event(e) => Some(*e),
804                            })
805                            .collect(),
806                    ),
807                    None => LanguageResult::EventSet(vec![]),
808                },
809            },
810            Expr::Unary(MonOp::Iota(a_e), arg) => {
811                self.quantifier_depth += 1;
812                let mut variables = variables.clone();
813                let domain: Either<_, _> = match a_e {
814                    ActorOrEvent::Actor => {
815                        Either::Left(scenario.actors.iter().copied().map(Entity::Actor))
816                    }
817                    ActorOrEvent::Event => Either::Right(
818                        (0..scenario.thematic_relations.len())
819                            .map(|x| Entity::Event(x.try_into().unwrap())),
820                    ),
821                };
822                let mut entity = None;
823                for e in domain {
824                    variables.set(self.quantifier_depth - 1, e);
825                    let value: bool = self.interp(*arg, scenario, &mut variables)?.try_into()?;
826                    if value && entity.is_some() {
827                        return Err(LanguageTypeError::PresuppositionError);
828                    } else if value {
829                        entity = Some(e);
830                    }
831                }
832                self.quantifier_depth -= 1;
833                match (entity, a_e) {
834                    (Some(Entity::Actor(a)), ActorOrEvent::Actor) => LanguageResult::Actor(a),
835                    (Some(Entity::Event(e)), ActorOrEvent::Event) => LanguageResult::Event(e),
836                    (None, _) => return Err(LanguageTypeError::PresuppositionError),
837                    _ => panic!("Should be impossible for the variable to not be an actor!"),
838                }
839            }
840
841            Expr::Unary(mon_op, arg) => {
842                let arg = self.interp(*arg, scenario, variables)?;
843                match mon_op {
844                    MonOp::Not => LanguageResult::Bool(!TryInto::<bool>::try_into(arg)?),
845                    MonOp::Property(e, ActorOrEvent::Actor) => {
846                        let arg: Actor = arg.try_into()?;
847                        match scenario.properties.get(e) {
848                            Some(property_members) => {
849                                LanguageResult::Bool(property_members.contains(&Entity::Actor(arg)))
850                            }
851                            None => LanguageResult::Bool(false),
852                        }
853                    }
854                    MonOp::Property(e, ActorOrEvent::Event) => {
855                        let arg: Event = arg.try_into()?;
856                        match scenario.properties.get(e) {
857                            Some(property_members) => {
858                                LanguageResult::Bool(property_members.contains(&Entity::Event(arg)))
859                            }
860                            None => LanguageResult::Bool(false),
861                        }
862                    }
863                    MonOp::Iota(_) => panic!("Captured before!"),
864                }
865            }
866        })
867    }
868}
869
870mod parser;
871pub use parser::LambdaParseError;
872pub use parser::parse_executable;
873use thiserror::Error;
874
875mod lambda_implementation;
876pub use lambda_implementation::ConjoiningError;
877
878#[cfg(feature = "sampling")]
879mod enumerator;
880
881#[cfg(feature = "sampling")]
882mod mutations;
883
884#[cfg(feature = "sampling")]
885pub use mutations::{
886    Context, LambdaEnumerator, LambdaSampler, PossibleExpressions, TypeAgnosticSampler,
887};
888
889mod serializations;
890
891#[cfg(test)]
892mod tests {
893    use crate::ScenarioDataset;
894    use std::collections::BTreeMap;
895
896    use super::*;
897    use crate::ThetaRoles;
898
899    #[test]
900    fn agent_of_and_patient_of() -> anyhow::Result<()> {
901        let simple_scenario = Scenario {
902            question: vec![],
903            actors: vec!["0", "1"],
904            thematic_relations: vec![ThetaRoles {
905                agent: Some("0"),
906                patient: None,
907            }],
908            properties: BTreeMap::default(),
909        };
910
911        let simple_expr = ExprPool(vec![
912            Expr::Actor("0"),
913            Expr::Event(0),
914            Expr::Binary(BinOp::AgentOf, ExprRef(0), ExprRef(1)),
915        ]);
916
917        let expr = LanguageExpression {
918            pool: simple_expr,
919            start: ExprRef(2),
920        };
921        assert_eq!(
922            expr.run(&simple_scenario, None)?,
923            LanguageResult::Bool(true)
924        );
925
926        let simple_expr = ExprPool(vec![
927            Expr::Actor("0"),
928            Expr::Event(0),
929            Expr::Binary(BinOp::PatientOf, ExprRef(0), ExprRef(1)),
930        ]);
931
932        let expr = LanguageExpression {
933            pool: simple_expr,
934            start: ExprRef(2),
935        };
936        assert_eq!(
937            expr.run(&simple_scenario, None).unwrap(),
938            LanguageResult::Bool(false)
939        );
940        Ok(())
941    }
942
943    #[test]
944    fn quantification() -> anyhow::Result<()> {
945        let simple_scenario = Scenario {
946            question: vec![],
947            actors: vec!["0", "1"],
948            thematic_relations: vec![
949                ThetaRoles {
950                    agent: Some("0"),
951                    patient: Some("0"),
952                },
953                ThetaRoles {
954                    agent: Some("1"),
955                    patient: Some("0"),
956                },
957            ],
958            properties: BTreeMap::default(),
959        };
960
961        //For all actors there exists an event such that they are its agent.
962        let simple_expr = ExprPool(vec![
963            Expr::Quantifier {
964                quantifier: Quantifier::Universal,
965                var_type: ActorOrEvent::Actor,
966                restrictor: ExprRef(1),
967                subformula: ExprRef(2),
968            },
969            Expr::Constant(Constant::Everyone),
970            Expr::Quantifier {
971                quantifier: Quantifier::Existential,
972                var_type: ActorOrEvent::Event,
973                restrictor: ExprRef(3),
974                subformula: ExprRef(4),
975            },
976            Expr::Constant(Constant::EveryEvent),
977            Expr::Binary(BinOp::AgentOf, ExprRef(5), ExprRef(6)),
978            Expr::Variable(Variable::Actor(1)),
979            Expr::Variable(Variable::Event(0)),
980        ]);
981
982        let expr = LanguageExpression {
983            pool: simple_expr,
984            start: ExprRef(0),
985        };
986        assert_eq!(
987            expr.run(&simple_scenario, None)?,
988            LanguageResult::Bool(true)
989        );
990
991        //For all actors there exists an event such that they are its patient.
992        let simple_expr = ExprPool(vec![
993            Expr::Quantifier {
994                quantifier: Quantifier::Universal,
995                var_type: ActorOrEvent::Actor,
996                restrictor: ExprRef(1),
997                subformula: ExprRef(2),
998            },
999            Expr::Constant(Constant::Everyone),
1000            Expr::Quantifier {
1001                quantifier: Quantifier::Existential,
1002                var_type: ActorOrEvent::Event,
1003                restrictor: ExprRef(3),
1004                subformula: ExprRef(4),
1005            },
1006            Expr::Constant(Constant::EveryEvent),
1007            Expr::Binary(BinOp::PatientOf, ExprRef(5), ExprRef(6)),
1008            Expr::Variable(Variable::Actor(1)),
1009            Expr::Variable(Variable::Event(0)),
1010        ]);
1011        let expr = LanguageExpression {
1012            pool: simple_expr,
1013            start: ExprRef(0),
1014        };
1015        assert_eq!(
1016            expr.run(&simple_scenario, None)?,
1017            LanguageResult::Bool(false)
1018        );
1019        Ok(())
1020    }
1021
1022    #[test]
1023    fn logic() -> anyhow::Result<()> {
1024        let simple_scenario = Scenario {
1025            question: vec![],
1026            actors: vec!["0", "1"],
1027            thematic_relations: vec![
1028                ThetaRoles {
1029                    agent: Some("0"),
1030                    patient: Some("0"),
1031                },
1032                ThetaRoles {
1033                    agent: Some("1"),
1034                    patient: Some("0"),
1035                },
1036            ],
1037            properties: BTreeMap::default(),
1038        };
1039
1040        assert_eq!(
1041            LanguageExpression {
1042                pool: ExprPool(vec![Expr::Constant(Constant::Contradiction)]),
1043                start: ExprRef(0)
1044            }
1045            .run(&simple_scenario, None)?,
1046            LanguageResult::Bool(false)
1047        );
1048
1049        assert_eq!(
1050            LanguageExpression {
1051                pool: ExprPool(vec![Expr::Constant(Constant::Tautology)]),
1052                start: ExprRef(0)
1053            }
1054            .run(&simple_scenario, None)?,
1055            LanguageResult::Bool(true)
1056        );
1057
1058        //\neg \bot
1059        let simple_expr = ExprPool(vec![
1060            Expr::Unary(MonOp::Not, ExprRef(1)),
1061            Expr::Constant(Constant::Contradiction),
1062        ]);
1063        let expr = LanguageExpression {
1064            pool: simple_expr,
1065            start: ExprRef(0),
1066        };
1067        assert_eq!(
1068            expr.run(&simple_scenario, None)?,
1069            LanguageResult::Bool(true)
1070        );
1071
1072        //\neg \top
1073        let simple_expr = ExprPool(vec![
1074            Expr::Unary(MonOp::Not, ExprRef(1)),
1075            Expr::Constant(Constant::Tautology),
1076        ]);
1077        let expr = LanguageExpression {
1078            pool: simple_expr,
1079            start: ExprRef(0),
1080        };
1081        assert_eq!(
1082            expr.run(&simple_scenario, None)?,
1083            LanguageResult::Bool(false)
1084        );
1085
1086        //(\neg \bot) \lor (\bot)
1087        let simple_expr = ExprPool(vec![
1088            Expr::Binary(BinOp::Or, ExprRef(1), ExprRef(3)),
1089            Expr::Unary(MonOp::Not, ExprRef(2)),
1090            Expr::Constant(Constant::Contradiction),
1091            Expr::Constant(Constant::Contradiction),
1092        ]);
1093        let expr = LanguageExpression {
1094            pool: simple_expr,
1095            start: ExprRef(0),
1096        };
1097        assert_eq!(
1098            expr.run(&simple_scenario, None)?,
1099            LanguageResult::Bool(true)
1100        );
1101
1102        //(\neg \bot) \and (\bot)
1103        let simple_expr = ExprPool(vec![
1104            Expr::Binary(BinOp::And, ExprRef(1), ExprRef(3)),
1105            Expr::Unary(MonOp::Not, ExprRef(2)),
1106            Expr::Constant(Constant::Contradiction),
1107            Expr::Constant(Constant::Contradiction),
1108        ]);
1109        let expr = LanguageExpression {
1110            pool: simple_expr,
1111            start: ExprRef(0),
1112        };
1113        assert_eq!(
1114            expr.run(&simple_scenario, None)?,
1115            LanguageResult::Bool(false)
1116        );
1117
1118        //For all actors there exists an event such that they are its patient and TOP.
1119        let simple_expr = ExprPool(vec![
1120            Expr::Quantifier {
1121                quantifier: Quantifier::Universal,
1122                var_type: ActorOrEvent::Actor,
1123                restrictor: ExprRef(1),
1124                subformula: ExprRef(2),
1125            },
1126            Expr::Constant(Constant::Everyone),
1127            Expr::Quantifier {
1128                quantifier: Quantifier::Existential,
1129                var_type: ActorOrEvent::Event,
1130                restrictor: ExprRef(3),
1131                subformula: ExprRef(4),
1132            },
1133            Expr::Constant(Constant::EveryEvent),
1134            Expr::Binary(BinOp::And, ExprRef(5), ExprRef(8)),
1135            Expr::Binary(BinOp::PatientOf, ExprRef(6), ExprRef(7)),
1136            Expr::Variable(Variable::Actor(1)),
1137            Expr::Variable(Variable::Event(0)),
1138            Expr::Constant(Constant::Tautology),
1139        ]);
1140        let expr = LanguageExpression {
1141            pool: simple_expr,
1142            start: ExprRef(0),
1143        };
1144        assert_eq!(
1145            expr.run(&simple_scenario, None)?,
1146            LanguageResult::Bool(false)
1147        );
1148        Ok(())
1149    }
1150
1151    #[test]
1152    fn properties() -> anyhow::Result<()> {
1153        let mut properties = BTreeMap::default();
1154        properties.insert("1", vec![Entity::Actor("0"), Entity::Actor("1")]);
1155        properties.insert("534", vec![Entity::Actor("1")]);
1156        let simple_scenario = Scenario {
1157            question: vec![],
1158            actors: vec!["0", "1"],
1159            thematic_relations: vec![
1160                ThetaRoles {
1161                    agent: Some("0"),
1162                    patient: Some("0"),
1163                },
1164                ThetaRoles {
1165                    agent: Some("1"),
1166                    patient: Some("0"),
1167                },
1168            ],
1169            properties,
1170        };
1171
1172        // everyone is of property type one.
1173        let simple_expr = ExprPool(vec![
1174            Expr::Quantifier {
1175                quantifier: Quantifier::Universal,
1176                var_type: ActorOrEvent::Actor,
1177                restrictor: ExprRef(1),
1178                subformula: ExprRef(2),
1179            },
1180            Expr::Constant(Constant::Everyone),
1181            Expr::Unary(MonOp::Property("1", ActorOrEvent::Actor), ExprRef(3)),
1182            Expr::Variable(Variable::Actor(0)),
1183        ]);
1184        let expr = LanguageExpression {
1185            pool: simple_expr,
1186            start: ExprRef(0),
1187        };
1188        assert_eq!(
1189            expr.run(&simple_scenario, None)?,
1190            LanguageResult::Bool(true)
1191        );
1192        // someone is of property type 534.
1193        let simple_expr = ExprPool(vec![
1194            Expr::Quantifier {
1195                quantifier: Quantifier::Existential,
1196                var_type: ActorOrEvent::Actor,
1197                restrictor: ExprRef(1),
1198                subformula: ExprRef(2),
1199            },
1200            Expr::Constant(Constant::Everyone),
1201            Expr::Unary(MonOp::Property("534", ActorOrEvent::Actor), ExprRef(3)),
1202            Expr::Variable(Variable::Actor(0)),
1203        ]);
1204        let expr = LanguageExpression {
1205            pool: simple_expr,
1206            start: ExprRef(0),
1207        };
1208        assert_eq!(
1209            expr.run(&simple_scenario, None)?,
1210            LanguageResult::Bool(true)
1211        );
1212        Ok(())
1213    }
1214
1215    #[test]
1216    fn complicated_restrictors() -> anyhow::Result<()> {
1217        let mut properties = BTreeMap::default();
1218        properties.insert("534", vec![Entity::Actor("1")]);
1219        properties.insert("235", vec![Entity::Event(0)]);
1220        properties.insert("2", vec![Entity::Actor("0")]);
1221        let simple_scenario = Scenario {
1222            question: vec![],
1223            actors: vec!["0", "1"],
1224            thematic_relations: vec![ThetaRoles {
1225                agent: Some("1"),
1226                patient: Some("0"),
1227            }],
1228            properties,
1229        };
1230
1231        // all property type 534 objects are agents of a 235-event
1232        let simple_expr = ExprPool(vec![
1233            Expr::Quantifier {
1234                quantifier: Quantifier::Universal,
1235                var_type: ActorOrEvent::Actor,
1236                restrictor: ExprRef(1),
1237                subformula: ExprRef(2),
1238            },
1239            Expr::Constant(Constant::Property("534", ActorOrEvent::Actor)),
1240            Expr::Quantifier {
1241                quantifier: Quantifier::Existential,
1242                var_type: ActorOrEvent::Event,
1243                restrictor: ExprRef(3),
1244                subformula: ExprRef(4),
1245            },
1246            Expr::Constant(Constant::Property("235", ActorOrEvent::Event)),
1247            Expr::Binary(BinOp::AgentOf, ExprRef(5), ExprRef(6)),
1248            Expr::Variable(Variable::Actor(1)),
1249            Expr::Variable(Variable::Event(0)),
1250        ]);
1251
1252        let expr = LanguageExpression {
1253            pool: simple_expr,
1254            start: ExprRef(0),
1255        };
1256        assert_eq!(
1257            expr.run(&simple_scenario, None)?,
1258            LanguageResult::Bool(true)
1259        );
1260        // all property type 2 objects are agents of a 235-event (which is false)
1261        let simple_expr = ExprPool(vec![
1262            Expr::Quantifier {
1263                quantifier: Quantifier::Universal,
1264                var_type: ActorOrEvent::Actor,
1265                restrictor: ExprRef(1),
1266                subformula: ExprRef(2),
1267            },
1268            Expr::Constant(Constant::Property("2", ActorOrEvent::Actor)),
1269            Expr::Quantifier {
1270                quantifier: Quantifier::Existential,
1271                var_type: ActorOrEvent::Event,
1272                restrictor: ExprRef(3),
1273                subformula: ExprRef(4),
1274            },
1275            Expr::Constant(Constant::Property("235", ActorOrEvent::Event)),
1276            Expr::Binary(BinOp::AgentOf, ExprRef(5), ExprRef(6)),
1277            Expr::Variable(Variable::Actor(1)),
1278            Expr::Variable(Variable::Event(0)),
1279        ]);
1280        let expr = LanguageExpression {
1281            pool: simple_expr,
1282            start: ExprRef(0),
1283        };
1284        assert_eq!(
1285            expr.run(&simple_scenario, None)?,
1286            LanguageResult::Bool(false)
1287        );
1288
1289        let mut properties = BTreeMap::default();
1290        properties.insert("3", vec![Entity::Actor("1"), Entity::Actor("2")]);
1291        properties.insert("2", vec![Entity::Actor("1"), Entity::Actor("3")]);
1292        properties.insert("4", vec![Entity::Event(0)]);
1293        let simple_scenario = Scenario {
1294            question: vec![],
1295            actors: vec!["0", "1", "2", "3", "4"],
1296            thematic_relations: vec![ThetaRoles {
1297                agent: Some("1"),
1298                patient: Some("0"),
1299            }],
1300            properties,
1301        };
1302        //All property type 2 and property type 3 actors are an agent of an event
1303        let simple_expr = ExprPool(vec![
1304            Expr::Quantifier {
1305                quantifier: Quantifier::Universal,
1306                var_type: ActorOrEvent::Actor,
1307                restrictor: ExprRef(1),
1308                subformula: ExprRef(6),
1309            },
1310            Expr::Binary(BinOp::And, ExprRef(2), ExprRef(4)),
1311            Expr::Unary(MonOp::Property("2", ActorOrEvent::Actor), ExprRef(3)),
1312            Expr::Variable(Variable::Actor(0)),
1313            Expr::Unary(MonOp::Property("3", ActorOrEvent::Actor), ExprRef(5)),
1314            Expr::Variable(Variable::Actor(0)), //5
1315            Expr::Quantifier {
1316                quantifier: Quantifier::Existential,
1317                var_type: ActorOrEvent::Actor,
1318                restrictor: ExprRef(7),
1319                subformula: ExprRef(8),
1320            },
1321            Expr::Constant(Constant::EveryEvent),
1322            Expr::Binary(BinOp::AgentOf, ExprRef(9), ExprRef(10)),
1323            Expr::Variable(Variable::Actor(1)),
1324            Expr::Variable(Variable::Event(0)),
1325        ]);
1326        let expr = LanguageExpression {
1327            pool: simple_expr,
1328            start: ExprRef(0),
1329        };
1330        assert_eq!(
1331            expr.run(&simple_scenario, None)?,
1332            LanguageResult::Bool(true)
1333        );
1334        //All property type 2 and property type 3 actors are patients of an event
1335        let simple_expr = ExprPool(vec![
1336            Expr::Quantifier {
1337                quantifier: Quantifier::Universal,
1338                var_type: ActorOrEvent::Actor,
1339                restrictor: ExprRef(1),
1340                subformula: ExprRef(6),
1341            },
1342            Expr::Binary(BinOp::And, ExprRef(2), ExprRef(4)),
1343            Expr::Unary(MonOp::Property("2", ActorOrEvent::Actor), ExprRef(3)),
1344            Expr::Variable(Variable::Actor(0)),
1345            Expr::Unary(MonOp::Property("3", ActorOrEvent::Actor), ExprRef(5)),
1346            Expr::Variable(Variable::Actor(0)), //5
1347            Expr::Quantifier {
1348                quantifier: Quantifier::Existential,
1349                var_type: ActorOrEvent::Event,
1350                restrictor: ExprRef(7),
1351                subformula: ExprRef(8),
1352            },
1353            Expr::Constant(Constant::EveryEvent),
1354            Expr::Binary(BinOp::PatientOf, ExprRef(9), ExprRef(10)),
1355            Expr::Variable(Variable::Actor(1)),
1356            Expr::Variable(Variable::Event(0)),
1357        ]);
1358        let expr = LanguageExpression {
1359            pool: simple_expr,
1360            start: ExprRef(0),
1361        };
1362        assert_eq!(
1363            expr.run(&simple_scenario, None)?,
1364            LanguageResult::Bool(false)
1365        );
1366        Ok(())
1367    }
1368
1369    #[test]
1370    fn error_handling() -> anyhow::Result<()> {
1371        let expr = parse_executable("some_e(y,pe_1,PatientOf(a_1,y))")?;
1372
1373        let a = Scenario {
1374            question: vec![],
1375            actors: vec!["1", "0"],
1376            thematic_relations: vec![ThetaRoles {
1377                agent: Some("0"),
1378                patient: Some("1"),
1379            }],
1380            properties: vec![("1", vec![Entity::Event(0)])].into_iter().collect(),
1381        };
1382
1383        let b = Scenario {
1384            question: vec![],
1385            actors: vec!["1"],
1386            thematic_relations: vec![ThetaRoles {
1387                agent: Some("1"),
1388                patient: None,
1389            }],
1390            properties: vec![("0", vec![Entity::Event(0)])].into_iter().collect(),
1391        };
1392        assert_eq!(
1393            expr.run(&b, None),
1394            Err(LanguageTypeError::PresuppositionError)
1395        );
1396        expr.run(&a, None)?;
1397
1398        Ok(())
1399    }
1400
1401    #[test]
1402    fn weird_and_not_behaviour() -> anyhow::Result<()> {
1403        let scenario = "\"Phil danced\" <John (man), Mary (woman), Susan (woman), Phil (man); {A: Phil (dance)}, {A: Mary (run)}>";
1404
1405        let labels = ScenarioDataset::parse(scenario)?;
1406
1407        let a = LanguageExpression::parse("every_e(x,pe_dance,AgentOf(a_Phil,x))")?;
1408        let b = LanguageExpression::parse("every_e(x,pe_dance,AgentOf(a_Mary,x))")?;
1409        let c = LanguageExpression::parse(
1410            "(every_e(x,pe_dance,AgentOf(a_Phil,x)))&~(every_e(x,pe_dance,AgentOf(a_Mary,x)))",
1411        )?;
1412        let scenario = labels.iter_scenarios().next().unwrap();
1413        assert_eq!(a.run(scenario, None)?, LanguageResult::Bool(true));
1414        assert_eq!(b.run(scenario, None)?, LanguageResult::Bool(false));
1415        assert_eq!(c.run(scenario, None)?, LanguageResult::Bool(true));
1416
1417        let pool = LanguageExpression::parse(
1418            "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))",
1419        )?;
1420        let labels = ScenarioDataset::parse(
1421            "\"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)",
1422        )?;
1423
1424        let config = ExecutionConfig::default().allow_empty_quantification();
1425        let scenario = labels.iter_scenarios().next().unwrap();
1426
1427        pool.run(scenario, Some(config))?;
1428
1429        let pool = LanguageExpression::parse(
1430            "some_e(x, all_e, AgentOf(a_John, x) & PatientOf(a_Mary, x) & pe_helps(x))",
1431        )?;
1432        let labels = ScenarioDataset::parse(
1433            "\"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)",
1434        )?;
1435
1436        let config = ExecutionConfig::default().allow_empty_quantification();
1437        let scenario = labels.iter_scenarios().next().unwrap();
1438
1439        assert_eq!(
1440            pool.run(scenario, Some(config))?,
1441            LanguageResult::Bool(true)
1442        );
1443
1444        Ok(())
1445    }
1446
1447    #[test]
1448    fn iota_tests() -> anyhow::Result<()> {
1449        let scenario = "\"The man danced\" <John (man), Mary (woman), Susan (woman); {A: John (dance)}, {A: Mary (run)}>";
1450
1451        let labels = ScenarioDataset::parse(scenario)?;
1452
1453        let a = LanguageExpression::parse("every_e(x,pe_dance,AgentOf(iota(x, pa_man(x)),x))")?;
1454        let b = LanguageExpression::parse("every_e(x,pe_dance,AgentOf(iota(x, pa_woman(x)),x))")?;
1455        let c = LanguageExpression::parse("every_e(x,pe_dance,AgentOf(iota(x, pa_red(x)),x))")?;
1456
1457        let d = LanguageExpression::parse("iota_e(x, pe_dance(x))")?;
1458        let scenario = labels.iter_scenarios().next().unwrap();
1459        assert_eq!(
1460            a.to_string(),
1461            "every_e(x, pe_dance, AgentOf(iota(y, pa_man(y)), x))"
1462        );
1463        assert_eq!(a.run(scenario, None)?, LanguageResult::Bool(true));
1464        assert_eq!(
1465            b.run(scenario, None),
1466            Err(LanguageTypeError::PresuppositionError)
1467        );
1468        assert_eq!(
1469            c.run(scenario, None),
1470            Err(LanguageTypeError::PresuppositionError)
1471        );
1472        assert_eq!(d.run(scenario, None), Ok(LanguageResult::Event(0)));
1473
1474        Ok(())
1475    }
1476}