grit_pattern_matcher/pattern/
if.rs

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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
use super::{
    functions::{Evaluator, FuncEvaluation},
    patterns::{Matcher, Pattern, PatternName},
    predicates::Predicate,
    State,
};
use crate::context::QueryContext;
use core::fmt::Debug;
use grit_util::{
    error::{GritPatternError, GritResult},
    AnalysisLogs,
};

#[derive(Debug, Clone)]
pub struct If<Q: QueryContext> {
    pub if_: Predicate<Q>,
    pub then: Pattern<Q>,
    pub else_: Pattern<Q>,
}
impl<Q: QueryContext> If<Q> {
    pub fn new(if_: Predicate<Q>, then: Pattern<Q>, else_: Option<Pattern<Q>>) -> Self {
        Self {
            if_,
            then,
            else_: else_.unwrap_or(Pattern::Top),
        }
    }
}

impl<Q: QueryContext> PatternName for If<Q> {
    fn name(&self) -> &'static str {
        "IF"
    }
}

impl<Q: QueryContext> Matcher<Q> for If<Q> {
    fn execute<'a>(
        &'a self,
        binding: &Q::ResolvedPattern<'a>,
        init_state: &mut State<'a, Q>,
        context: &'a Q::ExecContext<'a>,
        logs: &mut AnalysisLogs,
    ) -> GritResult<bool> {
        let mut state = init_state.clone();
        if self.if_.execute_func(&mut state, context, logs)?.predicator {
            *init_state = state;
            self.then.execute(binding, init_state, context, logs)
        } else {
            self.else_.execute(binding, init_state, context, logs)
        }
    }
}

#[derive(Debug, Clone)]
pub struct PrIf<Q: QueryContext> {
    pub if_: Predicate<Q>,
    pub then: Predicate<Q>,
    pub else_: Predicate<Q>,
}

impl<Q: QueryContext> PrIf<Q> {
    pub fn new(if_: Predicate<Q>, then: Predicate<Q>, else_: Option<Predicate<Q>>) -> Self {
        Self {
            if_,
            then,
            else_: else_.unwrap_or(Predicate::True),
        }
    }
}

impl<Q: QueryContext> PatternName for PrIf<Q> {
    fn name(&self) -> &'static str {
        "PREDICATE_IF"
    }
}

impl<Q: QueryContext> Evaluator<Q> for PrIf<Q> {
    fn execute_func<'a>(
        &'a self,
        init_state: &mut State<'a, Q>,
        context: &'a Q::ExecContext<'a>,
        logs: &mut AnalysisLogs,
    ) -> GritResult<FuncEvaluation<Q>> {
        let mut state = init_state.clone();
        let condition = self.if_.execute_func(&mut state, context, logs)?;
        if condition.ret_val.is_some() {
            return Err(GritPatternError::new(
                "Cannot return from within if condition",
            ));
        }
        if condition.predicator {
            *init_state = state;
            self.then.execute_func(init_state, context, logs)
        } else {
            self.else_.execute_func(init_state, context, logs)
        }
    }
}