srcwalk 0.2.5

Tree-sitter indexed lookups — smart code reading for AI agents
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
use std::path::Path;

use crate::types::QueryType;

/// Classify a query string into a `QueryType` by byte-pattern matching.
/// No regex engine — `matches!` compiles to a jump table.
pub fn classify(query: &str, scope: &Path) -> QueryType {
    // 0. Slash-wrapped regex — /pattern/ → regex content search.
    //    Must come before glob check: regex metacharacters ([, {, *) overlap with glob syntax.
    //    Only if the inner pattern contains regex metacharacters — otherwise /src/ would be
    //    misclassified as regex instead of a path.
    if query.len() >= 3 && query.starts_with('/') && query.ends_with('/') {
        let pattern = &query[1..query.len() - 1];
        if !pattern.is_empty() && has_regex_metachar(pattern) {
            return QueryType::Regex(pattern.into());
        }
    }

    // 1. Path with line suffix — e.g. src/lib.rs:123.
    // Parse from the last colon so POSIX filenames containing ':' still work when the
    // prefix resolves to a file. Only activate when the suffix is a positive integer.
    if let Some((path, line)) = parse_path_line(query, scope) {
        return QueryType::FilePathLine(path, line);
    }

    // 2. Glob — check first because globs can contain path separators.
    //    But only if no spaces: real globs don't have spaces, content like "import { X }" does.
    if !query.contains(' ')
        && query
            .bytes()
            .any(|b| matches!(b, b'*' | b'?' | b'{' | b'['))
    {
        return QueryType::Glob(query.into());
    }

    // 3. File path — contains separator or starts with ./ ../.
    //    Spaces are valid in real paths; filesystem existence is the tie-breaker
    //    that keeps prose like "TODO: fix this/that" from becoming a path.
    if looks_like_path_with_separator(query) {
        return match resolve_existing_path(query, scope) {
            Some(resolved) => QueryType::FilePath(resolved),
            None => QueryType::Fallthrough(query.into()),
        };
    }

    // 4. Starts with . — could be dotfile (.gitignore) or relative path
    if query.starts_with('.') {
        let resolved = scope.join(query);
        if resolved.try_exists().unwrap_or(false) {
            return QueryType::FilePath(resolved);
        }
    }

    // 5. Pure numeric — fall through cascade (try symbol, then content as fallback)
    if query.bytes().all(|b| b.is_ascii_digit()) {
        return QueryType::Fallthrough(query.into());
    }

    // 6. Bare filename — only check filesystem for queries that look like filenames
    //    (have an extension or match known extensionless names like README, Makefile, etc.)
    if looks_like_filename(query) {
        let resolved = scope.join(query);
        if resolved.try_exists().unwrap_or(false) {
            return QueryType::FilePath(resolved);
        }
        // Not found at scope root — glob fallback, but only if this isn't a dotted symbol
        // like "Auth.validate" which should fall through to identifier/symbol check
        if !is_dotted_symbol(query) {
            return QueryType::Glob(format!("**/{query}"));
        }
    }

    // 7. Identifier — no whitespace, starts with letter/underscore/$/@
    if is_identifier(query) {
        // Sub-classify: exact symbol vs concept
        if looks_like_exact_symbol(query) {
            return QueryType::Symbol(query.into());
        }
        return QueryType::Concept(query.into());
    }

    // 8. OR-pattern — "Foo|Bar|Baz" with no spaces, all parts valid identifiers.
    //    Common developer intent: multi-symbol grep (rg "A|B|C" equivalent).
    //    Wrap in word boundaries so "Foo|Bar" doesn't match "Foobar"/"Barbarian".
    if !query.contains(' ') && query.contains('|') {
        let parts: Vec<&str> = query.split('|').filter(|s| !s.is_empty()).collect();
        if parts.len() >= 2 && parts.iter().all(|p| is_identifier(p)) {
            return QueryType::Regex(format!(r"\b({query})\b"));
        }
    }

    // 9. Multi-word — could be concept phrase ("cli mode", "search flow")
    if query.contains(' ') && query.split_whitespace().count() <= 4 {
        let words: Vec<&str> = query.split_whitespace().collect();
        let all_simple = words.iter().all(|w| {
            !w.is_empty()
                && w.bytes()
                    .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
        });
        if all_simple {
            return QueryType::Concept(query.into());
        }
    }

    // 10. Everything else — fall through to symbol→content cascade.
    //    For raw plain-text/punctuation-heavy queries, prefer `rg` directly.
    QueryType::Fallthrough(query.into())
}

/// Does this single-token query look like an exact symbol name?
///
/// Heuristics (all generic, no domain knowledge):
/// - `PascalCase` (starts uppercase): `SearchResult`, `MapModel`, `AuthService`
/// - Contains `::` or `.`: `std::path`, `Auth.validate`
/// - `snake_case` with underscore: `handle_auth`, `is_test_file`
/// - Has mixed case after first char: `handleAuth`, `getElementById`
/// - Starts with `$` or `@`: `$ref`, `@decorator`
fn looks_like_exact_symbol(query: &str) -> bool {
    let bytes = query.as_bytes();
    if bytes.is_empty() {
        return false;
    }

    // Starts uppercase → PascalCase type/class name
    if bytes[0].is_ascii_uppercase() {
        return true;
    }

    // Contains :: or . → qualified symbol
    if query.contains("::") || query.contains('.') {
        return true;
    }

    // Contains underscore → snake_case identifier
    if query.contains('_') {
        return true;
    }

    // Contains hyphen → kebab-case identifier (component names, npm packages)
    if query.contains('-') {
        return true;
    }

    // Starts with $ or @ → special symbol
    if bytes[0] == b'$' || bytes[0] == b'@' {
        return true;
    }

    // camelCase: starts lowercase but has uppercase later → likely function/method name
    if bytes[0].is_ascii_lowercase() && bytes[1..].iter().any(u8::is_ascii_uppercase) {
        return true;
    }

    // Short all-lowercase without any symbol markers → concept, not symbol
    // e.g. "thinking", "alias", "cli", "mode", "config"
    false
}

fn parse_path_line(query: &str, scope: &Path) -> Option<(std::path::PathBuf, usize)> {
    let (path_part, line_part) = query.rsplit_once(':')?;
    if path_part.is_empty() || line_part.is_empty() {
        return None;
    }

    let line: usize = line_part.parse().ok()?;
    if line == 0 {
        return None;
    }

    let resolved = resolve_existing_path(path_part, scope)?;
    Some((resolved, line))
}

fn resolve_existing_path(query: &str, scope: &Path) -> Option<std::path::PathBuf> {
    let path = Path::new(query);
    let resolved = if path.is_absolute() {
        path.to_path_buf()
    } else {
        scope.join(path)
    };
    resolved.try_exists().unwrap_or(false).then_some(resolved)
}

fn looks_like_path_with_separator(query: &str) -> bool {
    !query.is_empty()
        && (query.starts_with('/')
            || query.starts_with("~/")
            || query.starts_with("./")
            || query.starts_with("../")
            || query.contains('/')
            || query.contains('\\'))
}

/// Does this query look path-like enough that fallback search should be called out.
pub fn looks_like_path_query(query: &str) -> bool {
    if query.contains(' ') || query.is_empty() {
        return false;
    }
    if query
        .bytes()
        .any(|b| matches!(b, b'*' | b'?' | b'{' | b'['))
    {
        return false;
    }
    query.starts_with('/')
        || query.starts_with("~/")
        || query.starts_with("./")
        || query.starts_with("../")
        || query.contains('/')
        || query.contains('\\')
        || looks_like_filename(query)
}

/// Does this query look like a filename? Has an extension, or matches known extensionless names.
fn looks_like_filename(query: &str) -> bool {
    if query.contains(' ') || query.contains('/') {
        return false;
    }
    // Has a dot followed by an extension (not just a dotfile)
    if let Some(dot_pos) = query.rfind('.') {
        if dot_pos > 0 && dot_pos < query.len() - 1 {
            return true;
        }
    }
    // Known extensionless filenames
    matches!(
        query,
        "README"
            | "LICENSE"
            | "Makefile"
            | "GNUmakefile"
            | "Dockerfile"
            | "Containerfile"
            | "Vagrantfile"
            | "Rakefile"
            | "Gemfile"
            | "Procfile"
            | "Justfile"
            | "Taskfile"
            | "CHANGELOG"
            | "CONTRIBUTING"
            | "AUTHORS"
            | "CODEOWNERS"
    )
}

/// Does the pattern contain regex metacharacters?
/// Used to distinguish `/pattern/` regex from `/path/` paths.
fn has_regex_metachar(s: &str) -> bool {
    s.bytes().any(|b| {
        matches!(
            b,
            b'(' | b')'
                | b'['
                | b']'
                | b'{'
                | b'}'
                | b'*'
                | b'+'
                | b'?'
                | b'|'
                | b'\\'
                | b'^'
                | b'$'
        )
    })
}

/// Known source-file extensions. If `after` matches one of these, treat as filename.
/// Anything else with identifier on both sides → dotted symbol (method/property access).
const FILE_EXTENSIONS: &[&str] = &[
    "rs", "go", "py", "pyi", "ts", "tsx", "js", "jsx", "mjs", "cjs", "java", "kt", "kts", "scala",
    "swift", "rb", "php", "cs", "c", "h", "cc", "cpp", "cxx", "hpp", "hh", "hxx", "m", "mm", "lua",
    "dart", "ex", "exs", "erl", "hrl", "elm", "hs", "clj", "cljs", "cljc", "ml", "mli", "fs",
    "fsi", "fsx", "vb", "pas", "pl", "pm", "r", "jl", "nim", "zig", "v", "sh", "bash", "zsh",
    "fish", "ps1", "bat", "cmd", "html", "htm", "css", "scss", "sass", "less", "vue", "svelte",
    "astro", "md", "mdx", "rst", "adoc", "txt", "tex", "yaml", "yml", "toml", "json", "jsonc",
    "json5", "xml", "ini", "cfg", "conf", "env", "proto", "graphql", "gql", "sql", "prisma",
    "wasm", "lock",
];

/// Is this a dotted symbol (method/property access) rather than a filename?
/// "Auth.validate", "std.path" → true (symbol)
/// "server.go", "config.yaml" → false (filename)
fn is_dotted_symbol(query: &str) -> bool {
    let Some(dot_pos) = query.rfind('.') else {
        return false;
    };
    if dot_pos == 0 || dot_pos >= query.len() - 1 {
        return false;
    }
    let before = &query[..dot_pos];
    let after = &query[dot_pos + 1..];
    // Both parts must be identifiers
    if !is_identifier(before) || !is_identifier(after) {
        return false;
    }
    // If `after` is a known file extension → filename, not symbol.
    let after_lower = after.to_ascii_lowercase();
    !FILE_EXTENSIONS.contains(&after_lower.as_str())
}

/// Identifier check without regex: first byte is [a-zA-Z_$@],
/// rest are [a-zA-Z0-9_$\.\-]. Tight loop over bytes.
pub fn is_identifier(s: &str) -> bool {
    let bytes = s.as_bytes();
    if bytes.is_empty() {
        return false;
    }
    let first_valid = matches!(
        bytes[0],
        b'a'..=b'z' | b'A'..=b'Z' | b'_' | b'$' | b'@'
    );
    first_valid
        && bytes[1..].iter().all(|&b| {
            matches!(
                b,
                b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | b'$' | b'.' | b'-'
            )
        })
}

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

    #[test]
    fn regex_patterns() {
        let scope = PathBuf::from(".");
        assert!(matches!(
            classify("/render(Call|Result)/", &scope),
            QueryType::Regex(_)
        ));
        assert!(matches!(
            classify("/renderC[a-z]+/", &scope),
            QueryType::Regex(_)
        ));
        assert!(matches!(
            classify("/renderC[a-z]{3}/", &scope),
            QueryType::Regex(_)
        ));
        assert!(matches!(
            classify("/renderC.*/", &scope),
            QueryType::Regex(_)
        ));
        // Single slash or empty pattern should not be regex
        assert!(!matches!(classify("//", &scope), QueryType::Regex(_)));
        // Inner slashes = path, not regex
        assert!(!matches!(
            classify("/src/lib.rs/", &scope),
            QueryType::Regex(_)
        ));
        assert!(!matches!(classify("/src/", &scope), QueryType::Regex(_)));
    }

    #[test]
    fn glob_patterns() {
        let scope = PathBuf::from(".");
        assert!(matches!(classify("*.test.ts", &scope), QueryType::Glob(_)));
        assert!(matches!(
            classify("src/**/*.rs", &scope),
            QueryType::Glob(_)
        ));
        assert!(matches!(classify("{a,b}.js", &scope), QueryType::Glob(_)));
    }

    #[test]
    fn identifiers() {
        let scope = PathBuf::from(".");
        assert!(matches!(
            classify("handleAuth", &scope),
            QueryType::Symbol(_)
        ));
        assert!(matches!(
            classify("handle_auth", &scope),
            QueryType::Symbol(_)
        ));
        assert!(matches!(
            classify("my-component", &scope),
            QueryType::Symbol(_)
        ));
        assert!(matches!(
            classify("AuthService.validate", &scope),
            QueryType::Symbol(_)
        ));
        assert!(matches!(classify("$ref", &scope), QueryType::Symbol(_)));
        assert!(matches!(classify("@types", &scope), QueryType::Symbol(_)));
    }

    #[test]
    fn content_queries() {
        let scope = PathBuf::from(".");
        // Pure numeric → fallthrough cascade (no longer Content)
        assert!(matches!(classify("404", &scope), QueryType::Fallthrough(_)));
        assert!(matches!(
            classify("TODO: fix this", &scope),
            QueryType::Fallthrough(_)
        ));
        assert!(matches!(
            classify("import { X }", &scope),
            QueryType::Fallthrough(_)
        ));
    }

    #[test]
    fn concept_queries() {
        let scope = PathBuf::from(".");
        // Single lowercase words → concept, not symbol
        assert!(matches!(
            classify("thinking", &scope),
            QueryType::Concept(_)
        ));
        assert!(matches!(classify("alias", &scope), QueryType::Concept(_)));
        assert!(matches!(classify("cli", &scope), QueryType::Concept(_)));
        assert!(matches!(classify("mode", &scope), QueryType::Concept(_)));
        assert!(matches!(classify("config", &scope), QueryType::Concept(_)));
        assert!(matches!(classify("server", &scope), QueryType::Concept(_)));
        // Multi-word phrases → concept
        assert!(matches!(
            classify("cli mode", &scope),
            QueryType::Concept(_)
        ));
        assert!(matches!(
            classify("search flow", &scope),
            QueryType::Concept(_)
        ));
        assert!(matches!(
            classify("model mapping", &scope),
            QueryType::Concept(_)
        ));
    }

    #[test]
    fn symbol_not_concept() {
        let scope = PathBuf::from(".");
        // PascalCase → symbol
        assert!(matches!(
            classify("SearchResult", &scope),
            QueryType::Symbol(_)
        ));
        assert!(matches!(classify("MapModel", &scope), QueryType::Symbol(_)));
        // camelCase → symbol
        assert!(matches!(
            classify("handleAuth", &scope),
            QueryType::Symbol(_)
        ));
        assert!(matches!(
            classify("thinkingBudget", &scope),
            QueryType::Symbol(_)
        ));
        // snake_case → symbol
        assert!(matches!(
            classify("is_test_file", &scope),
            QueryType::Symbol(_)
        ));
        assert!(matches!(
            classify("handle_auth", &scope),
            QueryType::Symbol(_)
        ));
        // dotted → symbol
        assert!(matches!(
            classify("Auth.validate", &scope),
            QueryType::Symbol(_)
        ));
    }

    #[test]
    fn is_identifier_checks() {
        assert!(is_identifier("handleAuth"));
        assert!(is_identifier("_private"));
        assert!(is_identifier("$ref"));
        assert!(is_identifier("@decorator"));
        assert!(is_identifier("my-component"));
        assert!(is_identifier("Auth.validate"));
        assert!(!is_identifier(""));
        assert!(!is_identifier("has space"));
        assert!(!is_identifier("123start"));
    }

    #[test]
    fn or_pattern_queries() {
        let scope = PathBuf::from(".");
        // Pipe-separated identifiers → regex
        assert!(matches!(
            classify("Config|Security|Auth", &scope),
            QueryType::Regex(_)
        ));
        assert!(matches!(
            classify("handleAuth|handleLogin", &scope),
            QueryType::Regex(_)
        ));
        assert!(matches!(
            classify("TODO|FIXME|HACK", &scope),
            QueryType::Regex(_)
        ));
        // Single part with trailing pipe → not regex (only 1 non-empty part)
        assert!(!matches!(classify("Foo|", &scope), QueryType::Regex(_)));
        // Non-identifier parts → not regex
        assert!(!matches!(
            classify("has space|also space", &scope),
            QueryType::Regex(_)
        ));
        // Already /wrapped/ → regex via step 0, not this check
        assert!(matches!(classify("/Foo|Bar/", &scope), QueryType::Regex(_)));
    }

    #[test]
    fn paths_with_spaces_are_file_paths_when_they_exist() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir
            .path()
            .join("source")
            .join("DNN Platform")
            .join("Modules")
            .join("DDRMenu")
            .join("Common")
            .join("Utilities.cs");
        std::fs::create_dir_all(file.parent().unwrap()).unwrap();
        std::fs::write(&file, "class Utilities {}\n").unwrap();

        let query = "source/DNN Platform/Modules/DDRMenu/Common/Utilities.cs";
        match classify(query, dir.path()) {
            QueryType::FilePath(path) => assert_eq!(path, file),
            other => panic!("expected FilePath, got {other:?}"),
        }
    }

    #[test]
    fn path_line_with_spaces_resolves_when_path_exists() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir
            .path()
            .join("source")
            .join("DNN Platform")
            .join("Utilities.cs");
        std::fs::create_dir_all(file.parent().unwrap()).unwrap();
        std::fs::write(&file, "class Utilities {}\n").unwrap();

        let query = "source/DNN Platform/Utilities.cs:7";
        match classify(query, dir.path()) {
            QueryType::FilePathLine(path, line) => {
                assert_eq!(path, file);
                assert_eq!(line, 7);
            }
            other => panic!("expected FilePathLine, got {other:?}"),
        }
    }

    #[test]
    fn bare_filename_glob_fallback() {
        // File that doesn't exist at scope root → glob fallback
        let scope = PathBuf::from(".");
        match classify("ProgramDB.java", &scope) {
            QueryType::FilePath(_) => {
                // Also acceptable if file happens to exist
            }
            QueryType::Glob(pattern) => {
                assert_eq!(pattern, "**/ProgramDB.java");
            }
            other => panic!("expected FilePath or Glob, got {other:?}"),
        }
        // Known extensionless filename that doesn't exist → glob
        match classify("Dockerfile", &scope) {
            QueryType::FilePath(_) => {} // exists in srcwalk repo
            QueryType::Glob(pattern) => {
                assert_eq!(pattern, "**/Dockerfile");
            }
            other => panic!("expected FilePath or Glob, got {other:?}"),
        }
    }
}