grit_pattern_matcher/pattern/
variable_content.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
use grit_util::error::{GritPatternError, GritResult};

use super::{resolved_pattern::ResolvedPattern, state::State, variable::Variable};
use crate::{context::QueryContext, pattern::patterns::Pattern};
use std::borrow::Cow;

#[derive(Debug, Clone)]
pub struct VariableContent<'a, Q: QueryContext> {
    pub name: String,
    pub pattern: Option<&'a Pattern<Q>>,
    // needs to be boxed for lifetime reasons
    pub value: Option<Q::ResolvedPattern<'a>>,
    pub value_history: Vec<Q::ResolvedPattern<'a>>,
    // If the value is a binding, whenever it is updated the mirrors should be updated as well
    pub mirrors: Vec<&'a Variable>,
}

impl<'a, Q: QueryContext> VariableContent<'a, Q> {
    pub fn new(name: String) -> Self {
        Self {
            name,
            pattern: None,
            value: None,
            value_history: vec![],
            mirrors: vec![],
        }
    }

    // should we return an option instead of a Result?
    // should we trace pattern calls here? - currently only used by variable which already traces
    pub fn text(
        &self,
        state: &State<'a, Q>,
        language: &Q::Language<'a>,
    ) -> GritResult<Cow<'a, str>> {
        if let Some(value) = &self.value {
            value.text(&state.files, language)
        } else {
            Err(GritPatternError::new(format!(
                "no value for variable {}",
                self.name
            )))
        }
    }

    pub(crate) fn set_value(&mut self, value: Q::ResolvedPattern<'a>) {
        self.value = Some(value);
    }
}