syntext 1.1.1

Hybrid code search index for agent workflows
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
//! Path/type glob filter using Roaring bitmaps from PathIndex.
//!
//! Produces a candidate file_id set that restricts which documents
//! enter the verification stage.

use std::path::Path;

use memchr::memmem;
use roaring::RoaringBitmap;

use crate::path_util::path_bytes;

use super::{ByteSplitExt, PathIndex};

/// A resolved path filter: a Roaring bitmap of matching file_ids.
pub struct PathFilter {
    /// Matching file_ids. Only documents in this set should be verified.
    pub file_ids: RoaringBitmap,
}

/// Build a `PathFilter` from search options against the given `PathIndex`.
///
/// - `file_type`: include only files with this extension (e.g. "rs").
/// - `exclude_type`: exclude files with this extension (e.g. "js").
/// - `path_glob`: simple glob-style match on the full relative path.
///
/// Returns `None` if no filter applies (all files are candidates).
pub fn build_filter(
    path_index: &PathIndex,
    file_type: Option<&str>,
    exclude_type: Option<&str>,
    path_glob: Option<&str>,
) -> Option<PathFilter> {
    let mut result: Option<RoaringBitmap> = None;

    if let Some(ext) = file_type {
        let ext_bitmap = path_index
            .files_with_extension(ext)
            .cloned()
            .unwrap_or_default();
        result = Some(match result {
            Some(r) => r & &ext_bitmap,
            None => ext_bitmap,
        });
    }

    if path_glob.is_some() {
        let mut glob_bitmap = RoaringBitmap::new();
        for (file_id, path) in path_index.visible_paths() {
            if matches_path_filter(path, file_type, exclude_type, path_glob) {
                glob_bitmap.insert(file_id);
            }
        }
        result = Some(match result {
            Some(r) => r & &glob_bitmap,
            None => glob_bitmap,
        });
    }

    if let Some(ext) = exclude_type {
        if let Some(ext_bitmap) = path_index.files_with_extension(ext) {
            result = Some(match result {
                Some(mut r) => {
                    r -= ext_bitmap;
                    r
                }
                None => {
                    let mut all = RoaringBitmap::new();
                    for (file_id, _) in path_index.visible_paths() {
                        all.insert(file_id);
                    }
                    all -= ext_bitmap;
                    all
                }
            });
        }
    }

    result.map(|file_ids| PathFilter { file_ids })
}

/// Check whether a path satisfies the same file type and path-glob semantics
/// used by `build_filter`.
pub(crate) fn matches_path_filter(
    path: &Path,
    file_type: Option<&str>,
    exclude_type: Option<&str>,
    path_glob: Option<&str>,
) -> bool {
    let path_bytes = path_bytes(path);
    let path_bytes = path_bytes.as_ref();

    if let Some(ext) = file_type {
        if !path_has_extension(path_bytes, ext.as_bytes()) {
            return false;
        }
    }

    if let Some(ext) = exclude_type {
        if path_has_extension(path_bytes, ext.as_bytes()) {
            return false;
        }
    }

    if let Some(glob) = path_glob {
        if !path_matches_glob(path, glob) {
            return false;
        }
    }

    true
}

/// Check if a path matches a simple glob pattern.
///
/// Supports:
/// - `*.ext`: match files by extension
/// - `**/*.ext`: match files by extension (recursive)
/// - `dir/`: match directory prefix
/// - `src/foo`: paths containing this exact segment sequence (has slash)
/// - Bare word `test`: match as a whole path component (filename or directory),
///   not as an arbitrary substring. Matches `test/`, `/test.rs`, `/test/`.
pub(crate) fn path_matches_glob(path: &Path, glob: &str) -> bool {
    let path_bytes = path_bytes(path);
    let path = path_bytes.as_ref();
    let glob = glob.as_bytes();

    if glob.starts_with(b"*.") && !glob.contains(&b'/') {
        return path_has_extension(path, &glob[2..]);
    }

    if let Some(rest) = glob.strip_prefix(b"**/") {
        if rest.starts_with(b"*.") && !rest.contains(&b'/') {
            return path_has_extension(path, &rest[2..]);
        }
        // Bare word (no '/' and no '*'): use component-boundary match, not
        // substring. "**/test" must NOT match "src/contest.rs".
        // Patterns with '/' (e.g., "**/src/test") keep substring semantics.
        if !rest.contains(&b'/') && !rest.contains(&b'*') {
            return path_has_component(path, rest);
        }
        return memmem::find(path, rest).is_some();
    }

    if glob.contains(&b'*') || glob.contains(&b'?') {
        if glob.contains(&b'/') {
            return path_glob_matches(path, glob);
        }
        return path
            .split(|&b| b == b'/')
            .any(|component| glob_matches_bytes(component, glob));
    }

    if glob.ends_with(b"/") {
        return path.starts_with(glob) || memmem::find(path, &[b"/", glob].concat()).is_some();
    }

    if glob.contains(&b'/') {
        return memmem::find(path, glob).is_some();
    }

    path_has_component(path, glob)
}

fn path_glob_matches(path: &[u8], glob: &[u8]) -> bool {
    if glob_matches_bytes(path, glob) {
        return true;
    }
    path.iter()
        .enumerate()
        .filter_map(|(idx, byte)| (*byte == b'/').then_some(idx + 1))
        .any(|start| glob_matches_bytes(&path[start..], glob))
}

fn glob_matches_bytes(text: &[u8], pattern: &[u8]) -> bool {
    let mut text_idx = 0usize;
    let mut pattern_idx = 0usize;
    let mut star_idx = None::<usize>;
    let mut star_text_idx = 0usize;

    while text_idx < text.len() {
        if pattern_idx < pattern.len()
            && (pattern[pattern_idx] == text[text_idx] || pattern[pattern_idx] == b'?')
        {
            text_idx += 1;
            pattern_idx += 1;
        } else if pattern_idx < pattern.len() && pattern[pattern_idx] == b'*' {
            star_idx = Some(pattern_idx);
            pattern_idx += 1;
            star_text_idx = text_idx;
        } else if let Some(star) = star_idx {
            pattern_idx = star + 1;
            star_text_idx += 1;
            text_idx = star_text_idx;
        } else {
            return false;
        }
    }

    while pattern_idx < pattern.len() && pattern[pattern_idx] == b'*' {
        pattern_idx += 1;
    }

    pattern_idx == pattern.len()
}

fn path_has_extension(path: &[u8], ext: &[u8]) -> bool {
    let Some(name) = path.rsplit(|&b| b == b'/').next() else {
        return false;
    };
    let Some((_, actual_ext)) = ByteSplitExt::rsplit_once(name, |&b| b == b'.') else {
        return false;
    };
    ascii_eq_ignore_case(actual_ext, ext)
}

fn path_has_component(path: &[u8], word: &[u8]) -> bool {
    for component in path.split(|&b| b == b'/') {
        if component == word {
            return true;
        }
        if let Some((stem, _)) = ByteSplitExt::rsplit_once(component, |&b| b == b'.') {
            if stem == word {
                return true;
            }
        }
    }
    false
}

fn ascii_eq_ignore_case(left: &[u8], right: &[u8]) -> bool {
    left.len() == right.len()
        && left
            .iter()
            .zip(right.iter())
            .all(|(l, r)| l.eq_ignore_ascii_case(r))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_index() -> PathIndex {
        let paths = vec![
            std::path::PathBuf::from("src/main.rs"),
            std::path::PathBuf::from("src/lib.rs"),
            std::path::PathBuf::from("src/util.py"),
            std::path::PathBuf::from("tests/test_main.rs"),
            std::path::PathBuf::from("docs/readme.md"),
            std::path::PathBuf::from("scripts/build.js"),
        ];
        PathIndex::build(&paths)
    }

    #[test]
    fn filter_by_extension() {
        let idx = make_index();
        let filter = build_filter(&idx, Some("rs"), None, None).unwrap();
        assert_eq!(filter.file_ids.len(), 3);
    }

    #[test]
    fn filter_by_path_glob() {
        let idx = make_index();
        let filter = build_filter(&idx, None, None, Some("src/")).unwrap();
        assert_eq!(filter.file_ids.len(), 3);
    }

    #[test]
    fn filter_combined_type_and_path() {
        let idx = make_index();
        let filter = build_filter(&idx, Some("rs"), None, Some("src/")).unwrap();
        assert_eq!(filter.file_ids.len(), 2);
    }

    #[test]
    fn filter_exclude_type() {
        let idx = make_index();
        let filter = build_filter(&idx, None, Some("js"), None).unwrap();
        assert_eq!(filter.file_ids.len(), 5);
    }

    #[test]
    fn no_filter_returns_none() {
        let idx = make_index();
        let filter = build_filter(&idx, None, None, None);
        assert!(filter.is_none());
    }

    #[test]
    fn glob_star_extension() {
        assert!(path_matches_glob(Path::new("src/main.rs"), "*.rs"));
        assert!(!path_matches_glob(Path::new("src/main.py"), "*.rs"));
    }

    #[test]
    fn glob_double_star_extension() {
        assert!(path_matches_glob(
            Path::new("deep/nested/file.rs"),
            "**/*.rs"
        ));
        assert!(!path_matches_glob(
            Path::new("deep/nested/file.py"),
            "**/*.rs"
        ));
    }

    #[test]
    fn matches_path_filter_combines_type_and_glob() {
        assert!(matches_path_filter(
            Path::new("src/main.rs"),
            Some("rs"),
            None,
            Some("src/")
        ));
        assert!(!matches_path_filter(
            Path::new("src/main.py"),
            Some("rs"),
            None,
            Some("src/")
        ));
        assert!(!matches_path_filter(
            Path::new("tests/main.rs"),
            Some("rs"),
            None,
            Some("src/")
        ));
    }

    #[test]
    fn bare_word_glob_requires_component_boundary() {
        assert!(path_matches_glob(Path::new("test/foo.rs"), "test"));
        assert!(path_matches_glob(Path::new("src/test.rs"), "test"));
        assert!(path_matches_glob(Path::new("src/test/util.rs"), "test"));
        assert!(!path_matches_glob(Path::new("src/contest.rs"), "test"));
        assert!(!path_matches_glob(Path::new("src/testing.rs"), "test"));
    }

    #[test]
    fn path_with_slash_still_uses_substring() {
        assert!(path_matches_glob(Path::new("src/test/foo.rs"), "src/test"));
        assert!(!path_matches_glob(Path::new("lib/test/foo.rs"), "src/test"));
    }

    #[test]
    fn wildcard_glob_matches_file_component() {
        assert!(path_matches_glob(
            Path::new("tests/search_tests.rs"),
            "*tests.rs"
        ));
        assert!(!path_matches_glob(
            Path::new("tests/search.rs"),
            "*tests.rs"
        ));
    }

    #[test]
    fn wildcard_glob_with_slash_matches_component_suffix() {
        assert!(path_matches_glob(Path::new("vendor/lib.rs"), "vendor/**"));
        assert!(path_matches_glob(
            Path::new("src/vendor/lib.rs"),
            "vendor/**"
        ));
        assert!(!path_matches_glob(
            Path::new("src/not_vendor/lib.rs"),
            "vendor/**"
        ));
    }

    #[test]
    fn double_star_slash_bare_word_requires_component_boundary() {
        assert!(
            !path_matches_glob(Path::new("src/contest.rs"), "**/test"),
            "**/test must not match 'contest.rs' (substring, not component)"
        );
        assert!(
            !path_matches_glob(Path::new("src/testing.rs"), "**/test"),
            "**/test must not match 'testing.rs'"
        );
        assert!(
            path_matches_glob(Path::new("test/foo.rs"), "**/test"),
            "**/test must match 'test/foo.rs'"
        );
        assert!(
            path_matches_glob(Path::new("src/test.rs"), "**/test"),
            "**/test must match 'src/test.rs' (stem matches component)"
        );
        assert!(
            path_matches_glob(Path::new("src/test/util.rs"), "**/test"),
            "**/test must match when test is a directory component"
        );
    }

    #[test]
    fn double_star_slash_with_slash_still_uses_substring() {
        assert!(path_matches_glob(
            Path::new("deep/src/test/util.rs"),
            "**/src/test"
        ));
        assert!(!path_matches_glob(
            Path::new("deep/lib/test/util.rs"),
            "**/src/test"
        ));
    }

    #[cfg(unix)]
    #[test]
    fn non_utf8_paths_participate_in_extension_and_glob_filters() {
        use std::ffi::OsString;
        use std::os::unix::ffi::OsStringExt;

        let path = std::path::PathBuf::from(OsString::from_vec(b"src/odd\xff.rs".to_vec()));
        assert!(matches_path_filter(&path, Some("rs"), None, Some("src/")));
        assert!(path_matches_glob(&path, "*.rs"));
        assert!(path_matches_glob(&path, "src/"));
    }

    #[test]
    fn byte_split_ext_no_sep() {
        let s: &[u8] = b"nodot";
        assert_eq!(ByteSplitExt::rsplit_once(s, |&b| b == b'.'), None);
    }

    #[test]
    fn byte_split_ext_last_sep() {
        let s: &[u8] = b"foo.bar.baz";
        let (head, tail) = ByteSplitExt::rsplit_once(s, |&b| b == b'.').unwrap();
        assert_eq!(head, b"foo.bar");
        assert_eq!(tail, b"baz");
    }
}