cqs 1.25.0

Code intelligence and RAG for AI agents. Semantic search, call graphs, impact analysis, type dependencies, and smart context assembly — in single tool calls. 54 languages + L5X/L5K PLC exports, 91.2% Recall@1 (BGE-large), 0.951 MRR (296 queries). Local ML, GPU-accelerated.
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
//! Structural pattern matching on code chunks.
//!
//! Heuristic regex-based patterns applied post-search.
//! NOT AST analysis — best-effort matching on source text.

use crate::language::Language;

// ---------------------------------------------------------------------------
// Macro: define_patterns!
//
// Generates from a single declaration table:
//   - `Pattern` enum with Debug, Clone, Copy, PartialEq, Eq
//   - `Display` impl (variant → name string)
//   - `FromStr` impl (name string → variant, with optional aliases)
//   - `Pattern::all_names()` — canonical names only
//
// Adding a pattern = one new line here. Display, FromStr, all_names() stay
// in sync automatically. Behavioral methods (`matches`, per-pattern fns)
// remain hand-written below.
// ---------------------------------------------------------------------------
/// Generates a `Pattern` enum with associated trait implementations for parsing and displaying structural patterns.
///
/// # Arguments
///
/// - `$variant`: Identifier for each enum variant
/// - `$name`: String literal for the primary name of the pattern
/// - `$alias`: Optional string literals for alternative names that map to the same variant
///
/// # Returns
///
/// Expands to:
/// - A `Pattern` enum with all specified variants
/// - `Display` impl that maps variants to their primary names
/// - `FromStr` impl that parses primary names and aliases (case-sensitive) into variants
/// - `all_names()` method returning a slice of all primary pattern names
///
/// # Errors
///
/// The `FromStr` implementation returns an error with a helpful message listing all valid pattern names when an unknown string is parsed.
macro_rules! define_patterns {
    ( $( $variant:ident => $name:expr $(, aliases = [ $($alias:expr),* ])? ; )* ) => {
        /// Known structural patterns
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        pub enum Pattern {
            $( $variant, )*
        }

        impl std::fmt::Display for Pattern {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                match self {
                    $( Pattern::$variant => write!(f, $name), )*
                }
            }
        }

        impl std::str::FromStr for Pattern {
            type Err = anyhow::Error;
            fn from_str(s: &str) -> Result<Self, Self::Err> {
                match s {
                    $( $name => Ok(Pattern::$variant), )*
                    $( $( $( $alias => Ok(Pattern::$variant), )* )? )*
                    _ => anyhow::bail!(
                        "Unknown pattern '{}'. Valid: {}",
                        s,
                        Self::all_names().join(", ")
                    ),
                }
            }
        }

        impl Pattern {
            /// All valid pattern names (for schema generation and validation)
            pub fn all_names() -> &'static [&'static str] {
                &[ $( $name, )* ]
            }
        }
    };
}

define_patterns! {
    Builder => "builder";
    ErrorSwallow => "error_swallow", aliases = ["error-swallow"];
    Async => "async";
    Mutex => "mutex";
    Unsafe => "unsafe";
    Recursion => "recursion";
}

impl Pattern {
    /// Check if a code chunk matches this pattern.
    ///
    /// If the language provides a specific structural matcher for this pattern
    /// (via `LanguageDef::structural_matchers`), uses that. Otherwise falls
    /// through to the generic heuristics.
    pub fn matches(&self, content: &str, name: &str, language: Option<Language>) -> bool {
        // Check for language-specific matcher first
        if let Some(lang) = language {
            if let Some(matchers) = lang.def().structural_matchers {
                let pattern_name = self.to_string();
                for (matcher_name, matcher_fn) in matchers {
                    if *matcher_name == pattern_name {
                        return matcher_fn(content, name);
                    }
                }
            }
        }

        // Fall through to generic heuristics
        match self {
            Self::Builder => matches_builder(content, name),
            Self::ErrorSwallow => matches_error_swallow(content, language),
            Self::Async => matches_async(content, language),
            Self::Mutex => matches_mutex(content, language),
            Self::Unsafe => matches_unsafe(content, language),
            Self::Recursion => matches_recursion(content, name),
        }
    }
}

/// Builder pattern: returns self/Self, method chaining
fn matches_builder(content: &str, _name: &str) -> bool {
    // Look for returning self/Self or &self/&mut self
    content.contains("-> Self")
        || content.contains("-> &Self")
        || content.contains("-> &mut Self")
        || content.contains("return self")
        || content.contains("return this")
        || (content.contains(".set") && content.contains("return"))
}

/// Error swallowing: catch/except with empty body, unwrap_or_default, _ => {}
fn matches_error_swallow(content: &str, language: Option<Language>) -> bool {
    match language {
        Some(Language::Rust) => {
            content.contains("unwrap_or_default()")
                || content.contains("unwrap_or(())")
                || content.contains(".ok();")
                || content.contains("_ => {}")
                || content.contains("_ => ()")
        }
        Some(Language::Python) => {
            content.contains("except:") && content.contains("pass")
                || content.contains("except Exception:")
                    && (content.contains("pass") || content.contains("..."))
        }
        Some(Language::TypeScript | Language::JavaScript) => {
            content.contains("catch") && content.contains("{}")
                || content.contains("catch (") && content.contains("// ignore")
        }
        Some(Language::Go) => {
            // Go: _ = err pattern
            content.contains("_ = err") || content.contains("_ = ")
        }
        _ => {
            // Generic heuristics
            content.contains("catch") && content.contains("{}")
                || content.contains("except") && content.contains("pass")
        }
    }
}

/// Determines whether the given content contains asynchronous programming constructs for the specified language.
///
/// Checks for language-specific async syntax patterns. For recognized languages (Rust, Python, TypeScript, JavaScript, Go), it searches for language-specific async keywords and operators. For unknown or unspecified languages, it performs a generic search for "async" or "await".
///
/// # Arguments
///
/// * `content` - The source code string to analyze
/// * `language` - Optional language identifier to determine which async patterns to search for
///
/// # Returns
///
/// `true` if the content contains async programming constructs for the given language, `false` otherwise.
fn matches_async(content: &str, language: Option<Language>) -> bool {
    match language {
        Some(Language::Rust) => content.contains("async fn") || content.contains(".await"),
        Some(Language::Python) => content.contains("async def") || content.contains("await "),
        Some(Language::TypeScript | Language::JavaScript) => {
            content.contains("async ") || content.contains("await ")
        }
        Some(Language::Go) => {
            content.contains("go func") || content.contains("go ") || content.contains("<-")
        }
        _ => content.contains("async") || content.contains("await"),
    }
}

/// Determines whether code content contains mutex or synchronization lock patterns based on the specified programming language.
///
/// # Arguments
///
/// * `content` - A string slice containing the code to analyze
/// * `language` - An optional Language enum specifying the programming language. If None, performs a generic case-insensitive search
///
/// # Returns
///
/// Returns `true` if the content contains language-specific mutex or lock patterns, `false` otherwise.
fn matches_mutex(content: &str, language: Option<Language>) -> bool {
    match language {
        Some(Language::Rust) => {
            content.contains("Mutex") || content.contains("RwLock") || content.contains(".lock()")
        }
        Some(Language::Python) => content.contains("Lock()") || content.contains("threading.Lock"),
        Some(Language::Go) => content.contains("sync.Mutex") || content.contains("sync.RWMutex"),
        _ => {
            content.contains("mutex")
                || content.contains("Mutex")
                || content.contains("lock()")
                || content.contains("Lock()")
        }
    }
}

/// Unsafe code patterns (primarily Rust and C)
fn matches_unsafe(content: &str, language: Option<Language>) -> bool {
    match language {
        Some(Language::Rust) => content.contains("unsafe "),
        Some(Language::C) => {
            // C is inherently unsafe, look for dangerous patterns
            content.contains("memcpy")
                || content.contains("strcpy")
                || content.contains("sprintf")
                || content.contains("gets(")
        }
        Some(Language::Go) => content.contains("unsafe.Pointer"),
        _ => content.contains("unsafe"),
    }
}

/// Recursion: function calls itself by name
fn matches_recursion(content: &str, name: &str) -> bool {
    if name.is_empty() {
        return false;
    }
    // Look for the function name appearing in its own body (excluding the definition line)
    let lines: Vec<&str> = content.lines().collect();
    if lines.len() <= 1 {
        return false;
    }
    // Skip first line (function signature) and check for self-reference
    let call_paren = format!("{}(", name);
    let call_space = format!("{} (", name);
    lines[1..]
        .iter()
        .any(|line| line.contains(&call_paren) || line.contains(&call_space))
}

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

    #[test]
    fn test_pattern_parse_all_variants() {
        assert!(matches!(
            "builder".parse::<Pattern>().unwrap(),
            Pattern::Builder
        ));
        assert!(matches!(
            "error_swallow".parse::<Pattern>().unwrap(),
            Pattern::ErrorSwallow
        ));
        assert!(matches!(
            "error-swallow".parse::<Pattern>().unwrap(),
            Pattern::ErrorSwallow
        ));
        assert!(matches!(
            "async".parse::<Pattern>().unwrap(),
            Pattern::Async
        ));
        assert!(matches!(
            "mutex".parse::<Pattern>().unwrap(),
            Pattern::Mutex
        ));
        assert!(matches!(
            "unsafe".parse::<Pattern>().unwrap(),
            Pattern::Unsafe
        ));
        assert!(matches!(
            "recursion".parse::<Pattern>().unwrap(),
            Pattern::Recursion
        ));
        assert!("unknown".parse::<Pattern>().is_err());
    }

    #[test]
    fn test_pattern_display_roundtrip() {
        for name in Pattern::all_names() {
            let p: Pattern = name.parse().unwrap();
            assert_eq!(p.to_string(), *name);
        }
    }

    #[test]
    fn test_all_names_covers_all_variants() {
        // Ensure all_names has the same count as the roundtrip test variants
        // If a new variant is added to Pattern but not to all_names(), this fails
        assert_eq!(Pattern::all_names().len(), 6);
        for name in Pattern::all_names() {
            assert!(
                name.parse::<Pattern>().is_ok(),
                "all_names entry '{}' failed to parse",
                name
            );
        }
    }

    #[test]
    fn test_builder_pattern() {
        let pat = Pattern::Builder;
        assert!(pat.matches(
            "fn with_name(self, name: &str) -> Self { ... }",
            "with_name",
            None
        ));
        assert!(pat.matches("fn build(self) -> &Self { ... }", "build", None));
        assert!(!pat.matches("fn foo() -> i32 { 42 }", "foo", None));
    }

    #[test]
    fn test_error_swallow_rust() {
        let pat = Pattern::ErrorSwallow;
        let lang = Some(Language::Rust);
        assert!(pat.matches("let _ = result.unwrap_or_default();", "", lang));
        assert!(pat.matches("result.ok();", "", lang));
        assert!(pat.matches("match x { Ok(v) => v, _ => {} }", "", lang));
        assert!(!pat.matches("let v = result?;", "", lang));
    }

    #[test]
    fn test_error_swallow_python() {
        let pat = Pattern::ErrorSwallow;
        let lang = Some(Language::Python);
        assert!(pat.matches("try:\n    foo()\nexcept:\n    pass", "", lang));
        assert!(pat.matches("try:\n    foo()\nexcept Exception:\n    pass", "", lang));
        assert!(!pat.matches(
            "try:\n    foo()\nexcept ValueError as e:\n    log(e)",
            "",
            lang
        ));
    }

    #[test]
    fn test_error_swallow_js() {
        let pat = Pattern::ErrorSwallow;
        let lang = Some(Language::JavaScript);
        assert!(pat.matches("try { foo(); } catch (e) {}", "", lang));
        assert!(pat.matches("try { foo(); } catch (e) { // ignore }", "", lang));
        assert!(!pat.matches("try { foo(); } catch (e) { console.log(e); }", "", lang));
    }

    #[test]
    fn test_async_rust() {
        let pat = Pattern::Async;
        assert!(pat.matches("async fn fetch() { ... }", "", Some(Language::Rust)));
        assert!(pat.matches("let r = client.get(url).await?;", "", Some(Language::Rust)));
        assert!(!pat.matches("fn sync_fetch() { ... }", "", Some(Language::Rust)));
    }

    #[test]
    fn test_async_python() {
        let pat = Pattern::Async;
        assert!(pat.matches("async def fetch():", "", Some(Language::Python)));
        assert!(pat.matches("result = await client.get(url)", "", Some(Language::Python)));
        assert!(!pat.matches("def sync_fetch():", "", Some(Language::Python)));
    }

    #[test]
    fn test_async_go() {
        let pat = Pattern::Async;
        let lang = Some(Language::Go);
        assert!(pat.matches("go func() { ... }()", "", lang));
        assert!(pat.matches("ch <- value", "", lang));
        assert!(!pat.matches("func sync() { ... }", "", lang));
    }

    #[test]
    fn test_mutex_rust() {
        let pat = Pattern::Mutex;
        let lang = Some(Language::Rust);
        assert!(pat.matches("let guard = data.lock().unwrap();", "", lang));
        assert!(pat.matches("let m = Mutex::new(0);", "", lang));
        assert!(pat.matches("let rw = RwLock::new(vec![]);", "", lang));
        assert!(!pat.matches("fn pure_function(x: i32) -> i32 { x + 1 }", "", lang));
    }

    #[test]
    fn test_unsafe_rust() {
        let pat = Pattern::Unsafe;
        assert!(pat.matches("unsafe { ptr::read(src) }", "", Some(Language::Rust)));
        assert!(!pat.matches("fn safe_function() { ... }", "", Some(Language::Rust)));
    }

    #[test]
    fn test_unsafe_c() {
        let pat = Pattern::Unsafe;
        let lang = Some(Language::C);
        assert!(pat.matches("memcpy(dst, src, n);", "", lang));
        assert!(pat.matches("strcpy(buf, input);", "", lang));
        assert!(pat.matches("sprintf(buf, fmt, arg);", "", lang));
        assert!(!pat.matches("int add(int a, int b) { return a + b; }", "", lang));
    }

    #[test]
    fn test_recursion_self_call() {
        let pat = Pattern::Recursion;
        let code =
            "fn factorial(n: u32) -> u32 {\n    if n <= 1 { 1 } else { n * factorial(n - 1) }\n}";
        assert!(pat.matches(code, "factorial", None));
    }

    #[test]
    fn test_recursion_no_self_call() {
        let pat = Pattern::Recursion;
        let code = "fn add(a: i32, b: i32) -> i32 {\n    a + b\n}";
        assert!(!pat.matches(code, "add", None));
    }

    #[test]
    fn test_recursion_empty_name() {
        let pat = Pattern::Recursion;
        assert!(!pat.matches("fn foo() { foo() }", "", None));
    }

    #[test]
    fn test_recursion_single_line() {
        let pat = Pattern::Recursion;
        // Single-line content should not match (can't distinguish sig from body)
        assert!(!pat.matches("fn foo() { foo() }", "foo", None));
    }

    #[test]
    fn test_structural_matchers_fallback() {
        // When no language-specific matcher exists, generic heuristics are used
        let pat = Pattern::Unsafe;
        // Rust has no structural_matchers set (None), so it falls through
        assert!(pat.matches("unsafe { ptr::read(p) }", "read_ptr", Some(Language::Rust)));
        assert!(!pat.matches("fn safe() -> i32 { 42 }", "safe", Some(Language::Rust)));
    }

    #[test]
    fn test_pattern_matches_no_language() {
        // None language should use generic heuristics
        let pat = Pattern::Async;
        assert!(pat.matches("async function fetch() {}", "fetch", None));
        assert!(!pat.matches("function sync() {}", "sync", None));
    }
}