sqry-core 6.0.19

Core library for sqry - semantic code search engine
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
/// Query classifier - determines whether a query is semantic, text, or hybrid
///
/// Classification rules:
/// - Semantic: Contains relation queries, symbol filters, AST node types
/// - Text: Contains regex metacharacters, literal patterns, comments
/// - Hybrid: Ambiguous queries that should try semantic first, then fallback
use regex::Regex;
use std::sync::OnceLock;

/// Query type classification result
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QueryType {
    /// Pure semantic (AST-based) search
    Semantic,
    /// Pure text/regex search
    Text,
    /// Try semantic first, fallback to text if no results
    Hybrid,
}

/// Query classifier
pub struct QueryClassifier;

impl QueryClassifier {
    /// Classify a query string into semantic, text, or hybrid
    ///
    /// # Examples
    ///
    /// ```
    /// use sqry_core::search::classifier::{QueryClassifier, QueryType};
    ///
    /// // Semantic patterns
    /// assert_eq!(QueryClassifier::classify("callers(foo)"), QueryType::Semantic);
    /// assert_eq!(QueryClassifier::classify("kind:function AND name:bar"), QueryType::Semantic);
    ///
    /// // Text patterns
    /// assert_eq!(QueryClassifier::classify("TODO: fix this"), QueryType::Text);
    /// assert_eq!(QueryClassifier::classify("^fn \\w+"), QueryType::Text);
    ///
    /// // Hybrid (ambiguous)
    /// assert_eq!(QueryClassifier::classify("find_user"), QueryType::Hybrid);
    /// ```
    #[must_use]
    pub fn classify(query: &str) -> QueryType {
        // Rule 1: Explicit semantic patterns
        if Self::is_semantic_pattern(query) {
            return QueryType::Semantic;
        }

        // Rule 2: Explicit text patterns
        if Self::is_text_pattern(query) {
            return QueryType::Text;
        }

        // Rule 3: Ambiguous - use hybrid mode
        QueryType::Hybrid
    }

    /// Check if query contains semantic indicators
    ///
    /// Optimized with compiled regex for single-pass matching
    fn is_semantic_pattern(query: &str) -> bool {
        // Compile regex once at first use
        static SEMANTIC_RE: OnceLock<Regex> = OnceLock::new();

        let re = SEMANTIC_RE.get_or_init(|| {
            Regex::new(
                r"(?x)
                callers[(:]  |   # callers(foo) or callers:foo
                callees[(:]  |   # callees(bar) or callees:bar
                imports[(:]  |   # imports(baz) or imports:baz
                exports[(:]  |   # exports(qux) or exports:qux
                returns[(:]  |   # returns(type) or returns:type
                impl:        |   # impl:Debug (CD Static Analysis trait implementation)
                duplicates:  |   # duplicates:body (CD Static Analysis duplicate detection)
                unused:      |   # unused:public (CD Static Analysis dead code)
                circular:    |   # circular:calls (CD Static Analysis cycle detection)
                kind:        |   # kind:function
                visibility:  |   # visibility:public
                scope\.      |   # scope.type, scope.name, scope.parent, scope.ancestor (P2-34)
                async:       |   # async:true
                static:      |   # static:false
                @            |   # @function.def
                ::           # foo::bar::baz
            ",
            )
            .expect("Failed to compile semantic pattern regex")
        });

        re.is_match(query)
    }

    /// Check if query contains text search indicators
    fn is_text_pattern(query: &str) -> bool {
        // Text indicators:
        // - Common code markers: TODO, FIXME, HACK, XXX, NOTE, BUG
        // - Regex anchors: ^, $
        // - Regex character classes: \b, \w, \d, \s
        // - Regex quantifiers: +, *, ?, {n,m}
        // - Regex groups: (...)
        // - Comment patterns: //, #, /*

        let markers = ["TODO", "FIXME", "HACK", "XXX", "NOTE", "BUG"];
        if markers.iter().any(|&m| query.contains(m)) {
            return true;
        }

        // Regex metacharacters (strong signal for text search)
        if query.starts_with('^') || query.ends_with('$') {
            return true;
        }

        // Character classes and escape sequences
        if query.contains("\\b")
            || query.contains("\\w")
            || query.contains("\\d")
            || query.contains("\\s")
            || query.contains("\\W")
            || query.contains("\\D")
            || query.contains("\\S")
        {
            return true;
        }

        // Comment patterns
        if query.contains("//") || query.starts_with('#') || query.contains("/*") {
            return true;
        }

        false
    }
}

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

    #[test]
    fn test_classify_semantic_relation_queries() {
        assert_eq!(
            QueryClassifier::classify("callers(foo)"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("callees(bar)"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("imports(baz)"),
            QueryType::Semantic
        );
    }

    #[test]
    fn test_classify_semantic_symbol_filters() {
        assert_eq!(
            QueryClassifier::classify("kind:function AND name:bar"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("visibility:public"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("async:true AND static:false"),
            QueryType::Semantic
        );
    }

    #[test]
    fn test_classify_semantic_scope_queries() {
        assert_eq!(
            QueryClassifier::classify("scope:module::class"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("foo::bar::baz"),
            QueryType::Semantic
        );
    }

    #[test]
    fn test_classify_semantic_ast_nodes() {
        assert_eq!(
            QueryClassifier::classify("@function.def"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("@class.name"),
            QueryType::Semantic
        );
    }

    #[test]
    fn test_classify_text_markers() {
        assert_eq!(QueryClassifier::classify("TODO: fix this"), QueryType::Text);
        assert_eq!(
            QueryClassifier::classify("FIXME: handle error"),
            QueryType::Text
        );
        assert_eq!(
            QueryClassifier::classify("HACK: temporary"),
            QueryType::Text
        );
        assert_eq!(QueryClassifier::classify("XXX: review"), QueryType::Text);
    }

    #[test]
    fn test_classify_text_regex_anchors() {
        assert_eq!(QueryClassifier::classify("^fn main"), QueryType::Text);
        assert_eq!(QueryClassifier::classify("error$"), QueryType::Text);
    }

    #[test]
    fn test_classify_text_regex_character_classes() {
        assert_eq!(QueryClassifier::classify("fn \\w+"), QueryType::Text);
        assert_eq!(QueryClassifier::classify("\\d{3}"), QueryType::Text);
        assert_eq!(QueryClassifier::classify("\\bfoo\\b"), QueryType::Text);
    }

    #[test]
    fn test_classify_text_comment_patterns() {
        assert_eq!(QueryClassifier::classify("// comment"), QueryType::Text);
        assert_eq!(QueryClassifier::classify("# TODO"), QueryType::Text);
        assert_eq!(QueryClassifier::classify("/* block */"), QueryType::Text);
    }

    #[test]
    fn test_classify_hybrid_ambiguous() {
        // Simple identifiers are ambiguous - could be semantic or text
        assert_eq!(QueryClassifier::classify("find_user"), QueryType::Hybrid);
        assert_eq!(QueryClassifier::classify("calculate"), QueryType::Hybrid);
        assert_eq!(QueryClassifier::classify("UserModel"), QueryType::Hybrid);
    }

    #[test]
    fn test_classify_hybrid_simple_patterns() {
        // Simple patterns without clear indicators
        assert_eq!(QueryClassifier::classify("error"), QueryType::Hybrid);
        assert_eq!(QueryClassifier::classify("config"), QueryType::Hybrid);
    }

    // Edge case tests (Phase 1.2)
    #[test]
    fn test_classify_edge_case_empty_query() {
        // Empty query should be hybrid (ambiguous)
        assert_eq!(QueryClassifier::classify(""), QueryType::Hybrid);
    }

    #[test]
    fn test_classify_edge_case_whitespace_only() {
        // Whitespace-only queries should be hybrid
        assert_eq!(QueryClassifier::classify("   "), QueryType::Hybrid);
        assert_eq!(QueryClassifier::classify("\t"), QueryType::Hybrid);
        assert_eq!(QueryClassifier::classify("\n"), QueryType::Hybrid);
        assert_eq!(QueryClassifier::classify("  \t\n  "), QueryType::Hybrid);
    }

    #[test]
    fn test_classify_edge_case_semantic_with_special_chars() {
        // Semantic patterns with special characters in values
        assert_eq!(
            QueryClassifier::classify("kind:function-name"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("kind:foo_bar"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("kind:foo.bar"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("callers(my::path::Foo)"),
            QueryType::Semantic
        );
    }

    #[test]
    fn test_classify_edge_case_colon_without_field() {
        // Colon without semantic field should be hybrid
        assert_eq!(QueryClassifier::classify(":foo"), QueryType::Hybrid);
        assert_eq!(QueryClassifier::classify("::"), QueryType::Semantic); // Double colon is semantic
        assert_eq!(QueryClassifier::classify(":::"), QueryType::Semantic); // Triple colon contains ::
    }

    #[test]
    fn test_classify_edge_case_mixed_semantic_and_text() {
        // If query contains both semantic AND text indicators, semantic wins
        assert_eq!(
            QueryClassifier::classify("kind:function AND TODO"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("@function TODO: fix"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("callers(foo) // comment"),
            QueryType::Semantic
        );
    }

    #[test]
    fn test_classify_edge_case_parentheses_without_semantic() {
        // Parentheses alone are not semantic
        assert_eq!(QueryClassifier::classify("(foo)"), QueryType::Hybrid);
        assert_eq!(QueryClassifier::classify("foo(bar)"), QueryType::Hybrid);
    }

    #[test]
    fn test_classify_edge_case_at_symbol_positions() {
        // @ anywhere in query is semantic
        assert_eq!(QueryClassifier::classify("@"), QueryType::Semantic);
        assert_eq!(QueryClassifier::classify("@function"), QueryType::Semantic);
        assert_eq!(QueryClassifier::classify("function@"), QueryType::Semantic);
        assert_eq!(QueryClassifier::classify("foo@bar"), QueryType::Semantic);
    }

    #[test]
    fn test_classify_edge_case_double_colon_positions() {
        // :: anywhere is semantic (symbol paths)
        assert_eq!(QueryClassifier::classify("::"), QueryType::Semantic);
        assert_eq!(QueryClassifier::classify("foo::bar"), QueryType::Semantic);
        assert_eq!(QueryClassifier::classify("::bar"), QueryType::Semantic);
        assert_eq!(QueryClassifier::classify("foo::"), QueryType::Semantic);
    }

    #[test]
    fn test_classify_edge_case_semantic_fields_case_sensitive() {
        // Field names are case-sensitive in the regex
        assert_eq!(
            QueryClassifier::classify("kind:function"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("KIND:function"),
            QueryType::Hybrid
        ); // uppercase not matched
        assert_eq!(
            QueryClassifier::classify("Kind:function"),
            QueryType::Hybrid
        ); // titlecase not matched
    }

    #[test]
    fn test_classify_edge_case_relation_with_colon() {
        // Relations can use both ( and :
        assert_eq!(
            QueryClassifier::classify("callers:foo"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("callees:bar"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("imports:baz"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("exports:qux"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("returns:Type"),
            QueryType::Semantic
        );
    }

    #[test]
    fn test_classify_edge_case_relation_with_parentheses() {
        // Relations can also use parentheses - test both branches of [(:]
        assert_eq!(
            QueryClassifier::classify("exports(MyType)"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("returns(Result<T>)"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("imports(std::collections)"),
            QueryType::Semantic
        );
    }

    #[test]
    fn test_classify_edge_case_boolean_fields() {
        // Boolean fields (async, static)
        assert_eq!(QueryClassifier::classify("async:true"), QueryType::Semantic);
        assert_eq!(
            QueryClassifier::classify("async:false"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("static:true"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("static:false"),
            QueryType::Semantic
        );
    }

    #[test]
    fn test_classify_edge_case_complex_queries() {
        // Complex multi-clause queries
        assert_eq!(
            QueryClassifier::classify("kind:function AND async:true"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("(callers(foo) OR callees(bar)) AND kind:struct"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("visibility:public AND scope:module::MyClass"),
            QueryType::Semantic
        );
    }

    #[test]
    fn test_classify_edge_case_text_false_positives() {
        // Ensure these are NOT classified as semantic
        assert_eq!(QueryClassifier::classify("caller"), QueryType::Hybrid); // missing (s
        assert_eq!(QueryClassifier::classify("foo:bar"), QueryType::Hybrid); // not a known field
        assert_eq!(QueryClassifier::classify("name:foo"), QueryType::Hybrid); // 'name' not in semantic regex
        assert_eq!(QueryClassifier::classify("type:Bar"), QueryType::Hybrid); // 'type' not in semantic regex
    }

    #[test]
    fn test_classify_edge_case_unicode() {
        // Unicode in queries (should work with regex)
        assert_eq!(QueryClassifier::classify("kind:函数"), QueryType::Semantic);
        assert_eq!(
            QueryClassifier::classify("foo::バー::baz"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("callers(αβγ)"),
            QueryType::Semantic
        );
    }

    // CD Static Analysis predicate tests
    #[test]
    fn test_classify_cd_duplicates_predicate() {
        assert_eq!(
            QueryClassifier::classify("duplicates:body"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("duplicates:signature"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("duplicates:struct"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("kind:function AND duplicates:body"),
            QueryType::Semantic
        );
    }

    #[test]
    fn test_classify_cd_unused_predicate() {
        assert_eq!(
            QueryClassifier::classify("unused:public"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("unused:private"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("unused:function"),
            QueryType::Semantic
        );
        assert_eq!(QueryClassifier::classify("unused:all"), QueryType::Semantic);
    }

    #[test]
    fn test_classify_cd_circular_predicate() {
        assert_eq!(
            QueryClassifier::classify("circular:calls"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("circular:imports"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("circular:all"),
            QueryType::Semantic
        );
    }

    #[test]
    fn test_classify_cd_combined_predicates() {
        // Multiple CD predicates together
        assert_eq!(
            QueryClassifier::classify("kind:function AND duplicates:body AND unused:public"),
            QueryType::Semantic
        );
        assert_eq!(
            QueryClassifier::classify("impl:Debug AND circular:calls"),
            QueryType::Semantic
        );
    }
}