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