grit_pattern_matcher/pattern/
rewrite.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
use super::{
    dynamic_snippet::DynamicPattern,
    functions::{Evaluator, FuncEvaluation},
    patterns::{Matcher, Pattern, PatternName},
    resolved_pattern::ResolvedPattern,
    variable_content::VariableContent,
    State,
};
use crate::{context::QueryContext, effects::Effect};
use core::fmt::Debug;
use grit_util::{
    error::{GritPatternError, GritResult},
    AnalysisLogs, EffectKind,
};
use std::borrow::Cow;

#[derive(Debug, Clone)]
pub struct Rewrite<Q: QueryContext> {
    pub left: Pattern<Q>,
    pub right: DynamicPattern<Q>,
    pub annotation: Option<String>,
}

impl<Q: QueryContext> Rewrite<Q> {
    pub fn new(left: Pattern<Q>, right: DynamicPattern<Q>, annotation: Option<String>) -> Self {
        Self {
            left,
            right,
            annotation,
        }
    }

    pub fn new_pattern(
        left: Pattern<Q>,
        right: DynamicPattern<Q>,
        annotation: Option<String>,
    ) -> Pattern<Q> {
        Pattern::Rewrite(Box::new(Rewrite {
            left,
            right,
            annotation,
        }))
    }

    /**
     * Execute a rewrite rule, returning the new binding.
     *
     * If called from a rewrite side-condition, the binding should be None.
     * In this case, the left-hand side must be a variable, and the binding
     * will be taken from the current state.
     *
     * If called from a rewrite pattern, the binding should be Some(the current node).
     */
    pub(crate) fn execute_generalized<'a>(
        &'a self,
        resolved: Option<&Q::ResolvedPattern<'a>>,
        state: &mut State<'a, Q>,
        context: &'a Q::ExecContext<'a>,
        logs: &mut AnalysisLogs,
    ) -> GritResult<bool> {
        let resolved = match resolved {
            Some(b) => {
                if !self.left.execute(b, state, context, logs)? {
                    return Ok(false);
                } else {
                    Cow::Borrowed(b)
                }
            }
            None => {
                if let Pattern::Variable(v) = &self.left {
                    let var = state.trace_var_mut(v);
                    if let Some(VariableContent {
                        value: Some(content),
                        ..
                    }) = state
                        .bindings
                        .get(var.try_scope().unwrap() as usize)
                        .and_then(|scope| {
                            scope.last().unwrap().get(var.try_index().unwrap() as usize)
                        })
                        .cloned()
                        .map(|b| *b)
                    {
                        Cow::Owned(content)
                    } else {
                        return Err(GritPatternError::new(format!("Variable {:?} not bound", v)));
                    }
                } else {
                    return Err(GritPatternError::new(
                        "Rewrite side-conditions must have variable on left-hand side",
                    ));
                }
            }
        };
        let Some(bindings) = resolved.get_bindings() else {
            return Err(
                GritPatternError::new(

            "variable on left hand side of rewrite side-conditions can only be bound to bindings"
                )
            );
        };
        let replacement: Q::ResolvedPattern<'_> =
            ResolvedPattern::from_dynamic_pattern(&self.right, state, context, logs)?;
        let effects = bindings.map(|b| Effect {
            binding: b.clone(),
            pattern: replacement.clone(),
            kind: EffectKind::Rewrite,
        });
        state.effects.extend(effects);
        Ok(true)
    }
}

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

impl<Q: QueryContext> Matcher<Q> for Rewrite<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> {
        self.execute_generalized(Some(binding), state, context, logs)
    }
}

impl<Q: QueryContext> Evaluator<Q> for Rewrite<Q> {
    fn execute_func<'a>(
        &'a self,
        state: &mut State<'a, Q>,
        context: &'a Q::ExecContext<'a>,
        logs: &mut AnalysisLogs,
    ) -> GritResult<FuncEvaluation<Q>> {
        let predicator = self.execute_generalized(None, state, context, logs)?;
        Ok(FuncEvaluation {
            predicator,
            ret_val: None,
        })
    }
}