grit_pattern_matcher/pattern/
dynamic_snippet.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
use super::{
    accessor::Accessor,
    call_built_in::CallBuiltIn,
    functions::{CallForeignFunction, CallFunction},
    list_index::ListIndex,
    patterns::{Matcher, PatternName},
    resolved_pattern::ResolvedPattern,
    variable::Variable,
    State,
};
use crate::context::{ExecContext, QueryContext};
use grit_util::{error::GritResult, AnalysisLogs};

#[derive(Debug, Clone)]
pub enum DynamicSnippetPart {
    String(String),
    Variable(Variable),
}

#[derive(Debug, Clone)]
pub struct DynamicSnippet {
    pub parts: Vec<DynamicSnippetPart>,
}

#[derive(Debug, Clone)]
pub struct DynamicList<Q: QueryContext> {
    pub elements: Vec<DynamicPattern<Q>>,
}

#[derive(Debug, Clone)]
pub enum DynamicPattern<Q: QueryContext> {
    Variable(Variable),
    Accessor(Box<Accessor<Q>>),
    ListIndex(Box<ListIndex<Q>>),
    Snippet(DynamicSnippet),
    List(DynamicList<Q>),
    CallBuiltIn(CallBuiltIn<Q>),
    CallFunction(CallFunction<Q>),
    CallForeignFunction(CallForeignFunction<Q>),
}

impl<Q: QueryContext> DynamicPattern<Q> {
    pub fn text<'a>(
        &'a self,
        state: &mut State<'a, Q>,
        context: &'a Q::ExecContext<'a>,
        logs: &mut AnalysisLogs,
    ) -> GritResult<String> {
        let resolved = Q::ResolvedPattern::from_dynamic_pattern(self, state, context, logs)?;
        Ok(resolved.text(&state.files, context.language())?.to_string())
    }

    /// Create a constant DynamicPattern from a string.
    pub fn from_str_constant(s: &str) -> GritResult<Self> {
        let parts = vec![DynamicSnippetPart::String(s.to_string())];
        Ok(DynamicPattern::Snippet(DynamicSnippet { parts }))
    }
}

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

impl<Q: QueryContext> Matcher<Q> for DynamicPattern<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> {
        if binding.text(&state.files, context.language())? == self.text(state, context, logs)? {
            Ok(true)
        } else {
            Ok(false)
        }
    }
}

impl PatternName for DynamicSnippet {
    fn name(&self) -> &'static str {
        "DYNAMIC_SNIPPET"
    }
}