grit_pattern_matcher/pattern/
not.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
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 Not<Q: QueryContext> {
    pub pattern: Pattern<Q>,
}

impl<Q: QueryContext> Not<Q> {
    pub fn new(pattern: Pattern<Q>) -> Self {
        Self { pattern }
    }
}

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

impl<Q: QueryContext> Matcher<Q> for Not<Q> {
    fn execute<'a>(
        &'a self,
        binding: &Q::ResolvedPattern<'a>,
        state: &mut State<'a, Q>,
        context: &'a Q::ExecContext<'a>,
        logs: &mut AnalysisLogs,
    ) -> GritResult<bool> {
        Ok(!self
            .pattern
            .execute(binding, &mut state.clone(), context, logs)?)
    }
}

#[derive(Debug, Clone)]
pub struct PrNot<Q: QueryContext> {
    pub(crate) predicate: Predicate<Q>,
}

impl<Q: QueryContext> PrNot<Q> {
    pub fn new(predicate: Predicate<Q>) -> Self {
        Self { predicate }
    }
}

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

impl<Q: QueryContext> Evaluator<Q> for PrNot<Q> {
    fn execute_func<'a>(
        &'a self,
        state: &mut State<'a, Q>,
        context: &'a Q::ExecContext<'a>,
        logs: &mut AnalysisLogs,
    ) -> GritResult<FuncEvaluation<Q>> {
        let res = self
            .predicate
            .execute_func(&mut state.clone(), context, logs)?;
        if res.ret_val.is_some() {
            return Err(GritPatternError::new(
                "Cannot return from within not clause",
            ));
        }
        Ok(FuncEvaluation {
            predicator: !res.predicator,
            ret_val: None,
        })
    }
}