grit_pattern_matcher/pattern/
not.rs

1use super::{
2    functions::{Evaluator, FuncEvaluation},
3    patterns::{Matcher, Pattern, PatternName},
4    predicates::Predicate,
5    State,
6};
7use crate::context::QueryContext;
8use core::fmt::Debug;
9use grit_util::{
10    error::{GritPatternError, GritResult},
11    AnalysisLogs,
12};
13
14#[derive(Debug, Clone)]
15pub struct Not<Q: QueryContext> {
16    pub pattern: Pattern<Q>,
17}
18
19impl<Q: QueryContext> Not<Q> {
20    pub fn new(pattern: Pattern<Q>) -> Self {
21        Self { pattern }
22    }
23}
24
25impl<Q: QueryContext> PatternName for Not<Q> {
26    fn name(&self) -> &'static str {
27        "NOT"
28    }
29}
30
31impl<Q: QueryContext> Matcher<Q> for Not<Q> {
32    fn execute<'a>(
33        &'a self,
34        binding: &Q::ResolvedPattern<'a>,
35        state: &mut State<'a, Q>,
36        context: &'a Q::ExecContext<'a>,
37        logs: &mut AnalysisLogs,
38    ) -> GritResult<bool> {
39        Ok(!self
40            .pattern
41            .execute(binding, &mut state.clone(), context, logs)?)
42    }
43}
44
45#[derive(Debug, Clone)]
46pub struct PrNot<Q: QueryContext> {
47    pub(crate) predicate: Predicate<Q>,
48}
49
50impl<Q: QueryContext> PrNot<Q> {
51    pub fn new(predicate: Predicate<Q>) -> Self {
52        Self { predicate }
53    }
54}
55
56impl<Q: QueryContext> PatternName for PrNot<Q> {
57    fn name(&self) -> &'static str {
58        "PREDICATE_NOT"
59    }
60}
61
62impl<Q: QueryContext> Evaluator<Q> for PrNot<Q> {
63    fn execute_func<'a>(
64        &'a self,
65        state: &mut State<'a, Q>,
66        context: &'a Q::ExecContext<'a>,
67        logs: &mut AnalysisLogs,
68    ) -> GritResult<FuncEvaluation<Q>> {
69        let res = self
70            .predicate
71            .execute_func(&mut state.clone(), context, logs)?;
72        if res.ret_val.is_some() {
73            return Err(GritPatternError::new(
74                "Cannot return from within not clause",
75            ));
76        }
77        Ok(FuncEvaluation {
78            predicator: !res.predicator,
79            ret_val: None,
80        })
81    }
82}