aboutsummaryrefslogtreecommitdiff
path: root/rprt-engine/src/monad.rs
blob: 34ff46b0e09f17c563cd3154feb485ad0c3f4ef8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use crate::{
    selection::{Selection, SelectionError},
    state::{EditorState, EvaluationResult, GroupedChangeError},
};

pub enum EvaluationStrategy {
    Sequential,
    Grouped,
}

#[derive(Debug)]
pub enum EvaluationError {
    Selection(SelectionError),
    GroupedChange(GroupedChangeError),
}

impl From<SelectionError> for EvaluationError {
    fn from(err: SelectionError) -> Self {
        EvaluationError::Selection(err)
    }
}

impl From<GroupedChangeError> for EvaluationError {
    fn from(err: GroupedChangeError) -> Self {
        EvaluationError::GroupedChange(err)
    }
}

pub struct EditorStateMonad {
    func: Box<dyn Fn(&EditorState) -> EvaluationResult>,
}

impl EditorStateMonad {
    pub fn new(f: impl Fn(&EditorState) -> EvaluationResult + 'static) -> Self {
        Self { func: Box::new(f) }
    }

    pub fn run(&self, state: &EditorState) -> EvaluationResult {
        (self.func)(state)
    }

    pub fn run_with_strategy(
        monads: Vec<EditorStateMonad>,
        strategy: EvaluationStrategy,
        state: &mut EditorState,
    ) -> Result<Selection, EvaluationError> {
        match strategy {
            EvaluationStrategy::Sequential => {
                let mut last_selection = Selection::empty();

                for monad in monads {
                    let (sel, state_changes) = monad.run(state);
                    state.commit_changes(state_changes);
                    last_selection = sel;
                }

                Ok(last_selection)
            }
            EvaluationStrategy::Grouped => {
                let mut arms = Vec::new();
                let mut all_selections = Vec::new();

                for monad in monads {
                    let (sel, state_changes) = monad.run(state);
                    all_selections.push(sel);
                    arms.push(state_changes);
                }

                state.commit_changes_grouped(arms)?;

                Ok(Selection::union(all_selections)?)
            }
        }
    }
}