grit_pattern_matcher/pattern/
like.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
use super::{
    patterns::{Matcher, Pattern, PatternName},
    State,
};
use crate::context::QueryContext;
use core::fmt::Debug;
use grit_util::error::{GritPatternError, GritResult};
use grit_util::AnalysisLogs;

#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct Like<Q: QueryContext> {
    pub like: Pattern<Q>,
    pub threshold: Pattern<Q>,
}

impl<Q: QueryContext> Like<Q> {
    pub fn new(like: Pattern<Q>, threshold: Pattern<Q>) -> Self {
        Self { like, threshold }
    }
}

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

impl<Q: QueryContext> Matcher<Q> for Like<Q> {
    #[cfg(feature = "embeddings")]
    fn execute<'a>(
        &'a self,
        binding: &Q::ResolvedPattern<'a>,
        state: &mut State<'a, Q>,
        context: &'a Q::ExecContext<'a>,
        logs: &mut AnalysisLogs,
    ) -> GritResult<bool> {
        use crate::errors::debug;

        let snippet = self.like.text(state, context, logs)?;
        let code = binding.text(&state.files)?.to_string();
        let model = embeddings::embed::EmbeddingModel::VoyageCode2;
        let similarity =
            model.similarity(snippet, code, context.runtime, |s| debug(logs, state, s))? as f64;
        Ok(similarity > self.threshold.float(state, context, logs)?)
    }

    #[cfg(not(feature = "embeddings"))]
    fn execute<'a>(
        &'a self,
        _binding: &Q::ResolvedPattern<'a>,
        _state: &mut State<'a, Q>,
        _context: &'a Q::ExecContext<'a>,
        _logs: &mut AnalysisLogs,
    ) -> GritResult<bool> {
        Err(GritPatternError::new(
            "Like only available under the embeddings feature",
        ))
    }
}