opengrep 1.1.0

Advanced AST-aware code search tool with tree-sitter parsing and AI integration capabilities
Documentation
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//! Pattern matching implementations
//!
//! This module provides different strategies for matching patterns in text,
//! including literal string matching and regular expression matching.

use anyhow::Result;
use regex::Regex;
use std::ops::Range;

/// Types of pattern matching
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MatchType {
    /// Literal string matching
    Literal,
    /// Regular expression matching
    Regex,
    /// Fuzzy matching (future implementation)
    Fuzzy,
}

/// Trait for pattern matchers
pub trait Matcher: Send + Sync {
    /// Find the first match in the given text
    fn find_match(&self, text: &str) -> Option<Range<usize>>;
    
    /// Find all matches in the given text
    fn find_all_matches(&self, text: &str) -> Vec<Range<usize>>;
    
    /// Get the match type
    fn match_type(&self) -> MatchType;
    
    /// Get the original pattern
    fn pattern(&self) -> &str;
    
    /// Check if the matcher is case-sensitive
    fn is_case_sensitive(&self) -> bool;
}

/// Literal string matcher
#[derive(Debug, Clone)]
pub struct LiteralMatcher {
    pattern: String,
    pattern_lower: String,
    case_sensitive: bool,
}

impl LiteralMatcher {
    /// Create a new literal matcher
    pub fn new(pattern: &str, ignore_case: bool) -> Self {
        Self {
            pattern: pattern.to_string(),
            pattern_lower: pattern.to_lowercase(),
            case_sensitive: !ignore_case,
        }
    }
}

impl Matcher for LiteralMatcher {
    fn find_match(&self, text: &str) -> Option<Range<usize>> {
        if self.case_sensitive {
            text.find(&self.pattern).map(|start| start..(start + self.pattern.len()))
        } else {
            text.to_lowercase().find(&self.pattern_lower)
                .map(|start| start..(start + self.pattern.len()))
        }
    }
    
    fn find_all_matches(&self, text: &str) -> Vec<Range<usize>> {
        let mut matches = Vec::new();
        let mut start = 0;
        
        if self.case_sensitive {
            while let Some(pos) = text[start..].find(&self.pattern) {
                let absolute_pos = start + pos;
                matches.push(absolute_pos..(absolute_pos + self.pattern.len()));
                start = absolute_pos + 1;
            }
        } else {
            let text_lower = text.to_lowercase();
            while let Some(pos) = text_lower[start..].find(&self.pattern_lower) {
                let absolute_pos = start + pos;
                matches.push(absolute_pos..(absolute_pos + self.pattern.len()));
                start = absolute_pos + 1;
            }
        }
        
        matches
    }
    
    fn match_type(&self) -> MatchType {
        MatchType::Literal
    }
    
    fn pattern(&self) -> &str {
        &self.pattern
    }
    
    fn is_case_sensitive(&self) -> bool {
        self.case_sensitive
    }
}

/// Regular expression matcher
#[derive(Debug)]
pub struct RegexMatcher {
    pattern: String,
    regex: Regex,
    case_sensitive: bool,
}

impl RegexMatcher {
    /// Create a new regex matcher
    pub fn new(pattern: &str, ignore_case: bool) -> Result<Self> {
        let mut regex_builder = regex::RegexBuilder::new(pattern);
        regex_builder.case_insensitive(ignore_case);
        
        let regex = regex_builder.build()
            .map_err(|e| anyhow::anyhow!("Invalid regex pattern '{}': {}", pattern, e))?;
        
        Ok(Self {
            pattern: pattern.to_string(),
            regex,
            case_sensitive: !ignore_case,
        })
    }
    
    /// Create a new regex matcher with custom flags
    pub fn with_flags(pattern: &str, flags: &str) -> Result<Self> {
        let mut regex_builder = regex::RegexBuilder::new(pattern);
        
        for flag in flags.chars() {
            match flag {
                'i' => { regex_builder.case_insensitive(true); }
                'm' => { regex_builder.multi_line(true); }
                's' => { regex_builder.dot_matches_new_line(true); }
                'x' => { regex_builder.ignore_whitespace(true); }
                'u' => { regex_builder.unicode(true); }
                _ => return Err(anyhow::anyhow!("Unknown regex flag: {}", flag)),
            }
        }
        
        let regex = regex_builder.build()
            .map_err(|e| anyhow::anyhow!("Invalid regex pattern '{}': {}", pattern, e))?;
        
        Ok(Self {
            pattern: pattern.to_string(),
            regex,
            case_sensitive: !flags.contains('i'),
        })
    }
}

impl Matcher for RegexMatcher {
    fn find_match(&self, text: &str) -> Option<Range<usize>> {
        self.regex.find(text).map(|m| m.range())
    }
    
    fn find_all_matches(&self, text: &str) -> Vec<Range<usize>> {
        self.regex.find_iter(text).map(|m| m.range()).collect()
    }
    
    fn match_type(&self) -> MatchType {
        MatchType::Regex
    }
    
    fn pattern(&self) -> &str {
        &self.pattern
    }
    
    fn is_case_sensitive(&self) -> bool {
        self.case_sensitive
    }
}

impl Clone for RegexMatcher {
    fn clone(&self) -> Self {
        Self::new(&self.pattern, !self.case_sensitive)
            .expect("Regex should be valid since it was created before")
    }
}

/// Fuzzy matcher for approximate string matching
#[derive(Debug, Clone)]
pub struct FuzzyMatcher {
    pattern: String,
    case_sensitive: bool,
    threshold: f64,
}

impl FuzzyMatcher {
    /// Create a new fuzzy matcher with the given similarity threshold
    pub fn new(pattern: &str, ignore_case: bool, threshold: f64) -> Self {
        Self {
            pattern: pattern.to_string(),
            case_sensitive: !ignore_case,
            threshold: threshold.clamp(0.0, 1.0),
        }
    }
    
    /// Calculate similarity between two strings using Levenshtein distance
    fn similarity(&self, a: &str, b: &str) -> f64 {
        let a = if self.case_sensitive { a } else { &a.to_lowercase() };
        let b = if self.case_sensitive { b } else { &b.to_lowercase() };
        
        if a == b {
            return 1.0;
        }
        
        let len_a = a.chars().count();
        let len_b = b.chars().count();
        
        if len_a == 0 || len_b == 0 {
            return 0.0;
        }
        
        let max_len = len_a.max(len_b);
        let distance = self.levenshtein_distance(a, b);
        
        1.0 - (distance as f64 / max_len as f64)
    }
    
    /// Calculate Levenshtein distance between two strings
    fn levenshtein_distance(&self, a: &str, b: &str) -> usize {
        let a_chars: Vec<char> = a.chars().collect();
        let b_chars: Vec<char> = b.chars().collect();
        let len_a = a_chars.len();
        let len_b = b_chars.len();
        
        if len_a == 0 { return len_b; }
        if len_b == 0 { return len_a; }
        
        let mut prev_row: Vec<usize> = (0..=len_b).collect();
        let mut curr_row = vec![0; len_b + 1];
        
        for i in 1..=len_a {
            curr_row[0] = i;
            
            for j in 1..=len_b {
                let cost = if a_chars[i - 1] == b_chars[j - 1] { 0 } else { 1 };
                curr_row[j] = (prev_row[j] + 1)
                    .min(curr_row[j - 1] + 1)
                    .min(prev_row[j - 1] + cost);
            }
            
            std::mem::swap(&mut prev_row, &mut curr_row);
        }
        
        prev_row[len_b]
    }
    
    /// Find fuzzy matches in a sliding window
    fn find_fuzzy_matches(&self, text: &str) -> Vec<Range<usize>> {
        let mut matches = Vec::new();
        let pattern_len = self.pattern.chars().count();
        let text_chars: Vec<char> = text.chars().collect();
        
        // Try different window sizes around the pattern length
        for window_size in (pattern_len.saturating_sub(2))..=(pattern_len + 2) {
            if window_size == 0 || window_size > text_chars.len() {
                continue;
            }
            
            for start in 0..=(text_chars.len() - window_size) {
                let end = start + window_size;
                let window: String = text_chars[start..end].iter().collect();
                
                if self.similarity(&self.pattern, &window) >= self.threshold {
                    let byte_start = text_chars[..start].iter().map(|c| c.len_utf8()).sum();
                    let byte_end = byte_start + window.len();
                    matches.push(byte_start..byte_end);
                }
            }
        }
        
        // Remove overlapping matches, keeping the best ones
        matches.sort_by_key(|range| range.start);
        self.deduplicate_overlapping_matches(matches)
    }
    
    /// Remove overlapping matches, keeping the best scoring ones
    fn deduplicate_overlapping_matches(&self, matches: Vec<Range<usize>>) -> Vec<Range<usize>> {
        if matches.is_empty() {
            return matches;
        }
        
        let mut result = vec![matches[0].clone()];
        
        for current in matches.into_iter().skip(1) {
            let last = result.last().unwrap();
            
            // Check if ranges overlap
            if current.start < last.end {
                // Keep the longer match (or first one if same length)
                if current.len() > last.len() {
                    result.pop();
                    result.push(current);
                }
            } else {
                result.push(current);
            }
        }
        
        result
    }
}

impl Matcher for FuzzyMatcher {
    fn find_match(&self, text: &str) -> Option<Range<usize>> {
        self.find_all_matches(text).into_iter().next()
    }
    
    fn find_all_matches(&self, text: &str) -> Vec<Range<usize>> {
        self.find_fuzzy_matches(text)
    }
    
    fn match_type(&self) -> MatchType {
        MatchType::Fuzzy
    }
    
    fn pattern(&self) -> &str {
        &self.pattern
    }
    
    fn is_case_sensitive(&self) -> bool {
        self.case_sensitive
    }
}

/// Create a matcher based on the given configuration
pub fn create_matcher(
    pattern: &str,
    match_type: MatchType,
    ignore_case: bool,
) -> Result<Box<dyn Matcher>> {
    match match_type {
        MatchType::Literal => Ok(Box::new(LiteralMatcher::new(pattern, ignore_case))),
        MatchType::Regex => Ok(Box::new(RegexMatcher::new(pattern, ignore_case)?)),
        MatchType::Fuzzy => Ok(Box::new(FuzzyMatcher::new(pattern, ignore_case, 0.8))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_literal_matcher() {
        let matcher = LiteralMatcher::new("test", false);
        
        assert_eq!(matcher.find_match("this is a test"), Some(10..14));
        assert_eq!(matcher.find_match("TEST case"), Some(0..4));
        assert_eq!(matcher.find_match("nothing here"), None);
        
        let matches = matcher.find_all_matches("test test test");
        assert_eq!(matches.len(), 3);
        assert_eq!(matches[0], 0..4);
        assert_eq!(matches[1], 5..9);
        assert_eq!(matches[2], 10..14);
    }
    
    #[test]
    fn test_literal_matcher_case_sensitive() {
        let matcher = LiteralMatcher::new("Test", true);
        
        assert_eq!(matcher.find_match("this is a Test"), Some(10..14));
        assert_eq!(matcher.find_match("this is a test"), None);
    }
    
    #[test]
    fn test_regex_matcher() {
        let matcher = RegexMatcher::new(r"\d+", false).unwrap();
        
        assert_eq!(matcher.find_match("hello 123 world"), Some(6..9));
        assert_eq!(matcher.find_match("no numbers here"), None);
        
        let matches = matcher.find_all_matches("123 and 456 and 789");
        assert_eq!(matches.len(), 3);
        assert_eq!(matches[0], 0..3);
        assert_eq!(matches[1], 8..11);
        assert_eq!(matches[2], 16..19);
    }
    
    #[test]
    fn test_regex_matcher_invalid() {
        let result = RegexMatcher::new("[invalid", false);
        assert!(result.is_err());
    }
    
    #[test]
    fn test_fuzzy_matcher() {
        let matcher = FuzzyMatcher::new("test", false, 0.7);
        
        // Exact match
        assert!(!matcher.find_all_matches("test").is_empty());
        
        // Similar match
        assert!(!matcher.find_all_matches("tset").is_empty());
        
        // Too different
        assert!(matcher.find_all_matches("hello").is_empty());
    }
    
    #[test]
    fn test_fuzzy_similarity() {
        let matcher = FuzzyMatcher::new("test", false, 0.8);
        
        assert_eq!(matcher.similarity("test", "test"), 1.0);
        assert!(matcher.similarity("test", "tset") > 0.5);
        assert!(matcher.similarity("test", "hello") < 0.5);
    }
    
    #[test]
    fn test_levenshtein_distance() {
        let matcher = FuzzyMatcher::new("test", false, 0.8);
        
        assert_eq!(matcher.levenshtein_distance("test", "test"), 0);
        assert_eq!(matcher.levenshtein_distance("test", "tset"), 2);
        assert_eq!(matcher.levenshtein_distance("test", "hello"), 5);
    }
    
    #[test]
    fn test_create_matcher() {
        let literal = create_matcher("test", MatchType::Literal, false).unwrap();
        assert_eq!(literal.match_type(), MatchType::Literal);
        
        let regex = create_matcher(r"\d+", MatchType::Regex, false).unwrap();
        assert_eq!(regex.match_type(), MatchType::Regex);
        
        let fuzzy = create_matcher("test", MatchType::Fuzzy, false).unwrap();
        assert_eq!(fuzzy.match_type(), MatchType::Fuzzy);
    }
    
    #[test]
    fn test_matcher_properties() {
        let matcher = LiteralMatcher::new("Test", true);
        assert_eq!(matcher.pattern(), "Test");
        assert!(matcher.is_case_sensitive());
        assert_eq!(matcher.match_type(), MatchType::Literal);
        
        let matcher = LiteralMatcher::new("test", false);
        assert!(!matcher.is_case_sensitive());
    }
}