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