cqs 1.22.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
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
//! Per-language doc comment format definitions.
//!
//! Each language has a `DocFormat` describing its comment syntax (prefix, line prefix,
//! suffix) and insertion position (before the function or inside the body).
//!
//! `format_doc_comment` takes raw LLM text and wraps it in the correct format
//! with proper indentation for the target language.

use crate::language::Language;

/// Doc comment format for a language.
#[derive(Debug, Clone, PartialEq)]
pub struct DocFormat {
    /// Block-open delimiter (e.g., `"/**"` for Java, `"\"\"\""` for Python).
    /// Empty string means no block-open line.
    pub prefix: &'static str,
    /// Per-line prefix (e.g., `"/// "` for Rust, `" * "` for Java).
    /// Empty string means no per-line prefix (content lines are bare).
    pub line_prefix: &'static str,
    /// Block-close delimiter (e.g., `" */"` for Java, `"\"\"\""` for Python).
    /// Empty string means no block-close line.
    pub suffix: &'static str,
    /// Where the doc comment is inserted relative to the function.
    pub position: InsertionPosition,
}

/// Where a doc comment is placed relative to the function definition.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InsertionPosition {
    /// Doc comment goes on lines immediately before the function signature.
    /// Used by most languages (Rust, Go, Java, C, etc.).
    BeforeFunction,
    /// Doc comment goes inside the function body (first statement).
    /// Used by Python (docstrings after `def`).
    InsideBody,
}

/// Returns the doc comment format for a given language.
/// Delegates to the `doc_format` field on `LanguageDef`, which each language
/// definition populates. The string tag is mapped to a `DocFormat` struct here.
pub fn doc_format_for(language: Language) -> DocFormat {
    let tag = language
        .try_def()
        .map(|d| d.doc_format)
        .unwrap_or("default");
    doc_format_from_tag(tag)
}

/// Map a doc format tag string to its concrete `DocFormat`.
fn doc_format_from_tag(tag: &str) -> DocFormat {
    match tag {
        "triple_slash" => DocFormat {
            prefix: "",
            line_prefix: "/// ",
            suffix: "",
            position: InsertionPosition::BeforeFunction,
        },
        "python_docstring" => DocFormat {
            prefix: "\"\"\"",
            line_prefix: "",
            suffix: "\"\"\"",
            position: InsertionPosition::InsideBody,
        },
        "go_comment" => DocFormat {
            prefix: "",
            line_prefix: "// ",
            suffix: "",
            position: InsertionPosition::BeforeFunction,
        },
        "javadoc" => DocFormat {
            prefix: "/**",
            line_prefix: " * ",
            suffix: " */",
            position: InsertionPosition::BeforeFunction,
        },
        "hash_comment" => DocFormat {
            prefix: "",
            line_prefix: "# ",
            suffix: "",
            position: InsertionPosition::BeforeFunction,
        },
        "elixir_doc" => DocFormat {
            prefix: "@doc \"\"\"",
            line_prefix: "",
            suffix: "\"\"\"",
            position: InsertionPosition::BeforeFunction,
        },
        "lua_ldoc" => DocFormat {
            prefix: "",
            line_prefix: "--- ",
            suffix: "",
            position: InsertionPosition::BeforeFunction,
        },
        "haskell_haddock" => DocFormat {
            prefix: "",
            line_prefix: "-- | ",
            suffix: "",
            position: InsertionPosition::BeforeFunction,
        },
        "ocaml_doc" => DocFormat {
            prefix: "(** ",
            line_prefix: "",
            suffix: " *)",
            position: InsertionPosition::BeforeFunction,
        },
        "erlang_edoc" => DocFormat {
            prefix: "",
            line_prefix: "%% ",
            suffix: "",
            position: InsertionPosition::BeforeFunction,
        },
        "r_roxygen" => DocFormat {
            prefix: "",
            line_prefix: "#' ",
            suffix: "",
            position: InsertionPosition::BeforeFunction,
        },
        "block_comment" => DocFormat {
            prefix: "(*",
            line_prefix: "",
            suffix: "*)",
            position: InsertionPosition::BeforeFunction,
        },
        // "default" and any unknown tag
        _ => DocFormat {
            prefix: "",
            line_prefix: "// ",
            suffix: "",
            position: InsertionPosition::BeforeFunction,
        },
    }
}

/// Format raw doc text into a language-specific doc comment with indentation.
/// Takes the raw LLM-generated doc text (plain prose, possibly multi-line) and
/// wraps it in the correct doc comment syntax for the target language.
/// # Arguments
/// * `text` - Raw doc text from LLM (no comment markers)
/// * `language` - Target language (determines format)
/// * `indent` - Indentation prefix for each line (spaces/tabs matching the function)
/// * `func_name` - Function name (used by Go convention: "// FuncName does X")
/// # Returns
/// Formatted doc comment string ready to insert into source, including trailing newline.
pub fn format_doc_comment(text: &str, language: Language, indent: &str, func_name: &str) -> String {
    let _span = tracing::debug_span!("format_doc_comment", func_name, ?language).entered();
    let format = doc_format_for(language);
    let lines: Vec<&str> = text.lines().collect();

    // Handle empty text
    if lines.is_empty() {
        return String::new();
    }

    let mut result = String::new();

    // For Go: prepend function name to first line per convention
    let go_first_line: String;
    let effective_lines: Vec<&str> = if language == Language::Go {
        if let Some(&first) = lines.first() {
            // "FuncName does X" — capitalize first char of description if needed
            go_first_line = format!("{func_name} {first}");
            let mut v = vec![go_first_line.as_str()];
            v.extend_from_slice(&lines[1..]);
            v
        } else {
            lines.clone()
        }
    } else {
        lines.clone()
    };

    // Emit prefix line if non-empty
    if !format.prefix.is_empty() {
        result.push_str(indent);
        result.push_str(format.prefix);
        result.push('\n');
    }

    // Emit content lines
    for line in &effective_lines {
        result.push_str(indent);
        result.push_str(format.line_prefix);
        result.push_str(line);
        result.push('\n');
    }

    // Emit suffix line if non-empty
    if !format.suffix.is_empty() {
        result.push_str(indent);
        result.push_str(format.suffix);
        result.push('\n');
    }

    result
}

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

    // ── Format registry tests ──────────────────────────────────────────

    #[test]
    fn test_rust_format() {
        let fmt = doc_format_for(Language::Rust);
        assert_eq!(fmt.prefix, "");
        assert_eq!(fmt.line_prefix, "/// ");
        assert_eq!(fmt.suffix, "");
        assert_eq!(fmt.position, InsertionPosition::BeforeFunction);
    }

    #[test]
    fn test_python_format() {
        let fmt = doc_format_for(Language::Python);
        assert_eq!(fmt.prefix, "\"\"\"");
        assert_eq!(fmt.line_prefix, "");
        assert_eq!(fmt.suffix, "\"\"\"");
        assert_eq!(fmt.position, InsertionPosition::InsideBody);
    }

    #[test]
    fn test_go_format() {
        let fmt = doc_format_for(Language::Go);
        assert_eq!(fmt.prefix, "");
        assert_eq!(fmt.line_prefix, "// ");
        assert_eq!(fmt.suffix, "");
        assert_eq!(fmt.position, InsertionPosition::BeforeFunction);
    }

    #[test]
    fn test_java_format() {
        let fmt = doc_format_for(Language::Java);
        assert_eq!(fmt.prefix, "/**");
        assert_eq!(fmt.line_prefix, " * ");
        assert_eq!(fmt.suffix, " */");
        assert_eq!(fmt.position, InsertionPosition::BeforeFunction);
    }

    #[test]
    fn test_typescript_format() {
        let fmt = doc_format_for(Language::TypeScript);
        assert_eq!(fmt.prefix, "/**");
        assert_eq!(fmt.line_prefix, " * ");
        assert_eq!(fmt.suffix, " */");
        assert_eq!(fmt.position, InsertionPosition::BeforeFunction);
    }

    #[test]
    fn test_fsharp_format() {
        let fmt = doc_format_for(Language::FSharp);
        assert_eq!(fmt.prefix, "");
        assert_eq!(fmt.line_prefix, "/// ");
        assert_eq!(fmt.suffix, "");
        assert_eq!(fmt.position, InsertionPosition::BeforeFunction);
    }

    #[test]
    fn test_ruby_format() {
        let fmt = doc_format_for(Language::Ruby);
        assert_eq!(fmt.prefix, "");
        assert_eq!(fmt.line_prefix, "# ");
        assert_eq!(fmt.suffix, "");
        assert_eq!(fmt.position, InsertionPosition::BeforeFunction);
    }

    #[test]
    fn test_elixir_format() {
        let fmt = doc_format_for(Language::Elixir);
        assert_eq!(fmt.prefix, "@doc \"\"\"");
        assert_eq!(fmt.line_prefix, "");
        assert_eq!(fmt.suffix, "\"\"\"");
        assert_eq!(fmt.position, InsertionPosition::BeforeFunction);
    }

    #[test]
    fn test_lua_format() {
        let fmt = doc_format_for(Language::Lua);
        assert_eq!(fmt.prefix, "");
        assert_eq!(fmt.line_prefix, "--- ");
        assert_eq!(fmt.suffix, "");
        assert_eq!(fmt.position, InsertionPosition::BeforeFunction);
    }

    #[test]
    fn test_haskell_format() {
        let fmt = doc_format_for(Language::Haskell);
        assert_eq!(fmt.prefix, "");
        assert_eq!(fmt.line_prefix, "-- | ");
        assert_eq!(fmt.suffix, "");
        assert_eq!(fmt.position, InsertionPosition::BeforeFunction);
    }

    #[test]
    fn test_ocaml_format() {
        let fmt = doc_format_for(Language::OCaml);
        assert_eq!(fmt.prefix, "(** ");
        assert_eq!(fmt.line_prefix, "");
        assert_eq!(fmt.suffix, " *)");
        assert_eq!(fmt.position, InsertionPosition::BeforeFunction);
    }

    #[test]
    fn test_default_format_for_unknown_language() {
        // Bash has no specific doc format, should get default //
        let fmt = doc_format_for(Language::Bash);
        assert_eq!(fmt.prefix, "");
        assert_eq!(fmt.line_prefix, "// ");
        assert_eq!(fmt.suffix, "");
        assert_eq!(fmt.position, InsertionPosition::BeforeFunction);
    }

    // ── format_doc_comment tests ───────────────────────────────────────

    #[test]
    fn test_format_rust_single_line() {
        let result =
            format_doc_comment("Returns the sum of two numbers.", Language::Rust, "", "add");
        assert_eq!(result, "/// Returns the sum of two numbers.\n");
    }

    #[test]
    fn test_format_rust_multiline() {
        let text = "Returns the sum of two numbers.\n\nPanics if overflow occurs.";
        let result = format_doc_comment(text, Language::Rust, "", "add");
        assert_eq!(
            result,
            "/// Returns the sum of two numbers.\n/// \n/// Panics if overflow occurs.\n"
        );
    }

    #[test]
    fn test_format_rust_with_indent() {
        let result =
            format_doc_comment("Does something useful.", Language::Rust, "    ", "process");
        assert_eq!(result, "    /// Does something useful.\n");
    }

    #[test]
    fn test_format_python_single_line() {
        let result = format_doc_comment(
            "Returns the sum of two numbers.",
            Language::Python,
            "    ",
            "add",
        );
        assert_eq!(
            result,
            "    \"\"\"\n    Returns the sum of two numbers.\n    \"\"\"\n"
        );
    }

    #[test]
    fn test_format_python_multiline() {
        let text = "Calculate the sum.\n\nArgs:\n    a: First number.\n    b: Second number.";
        let result = format_doc_comment(text, Language::Python, "    ", "add");
        let expected = "    \"\"\"\n    Calculate the sum.\n    \n    Args:\n        a: First number.\n        b: Second number.\n    \"\"\"\n";
        assert_eq!(result, expected);
    }

    #[test]
    fn test_format_go_prepends_func_name() {
        let result = format_doc_comment("returns the sum of two numbers.", Language::Go, "", "Add");
        assert_eq!(result, "// Add returns the sum of two numbers.\n");
    }

    #[test]
    fn test_format_go_multiline() {
        let text = "returns the sum of two numbers.\n\nIt panics on overflow.";
        let result = format_doc_comment(text, Language::Go, "", "Add");
        assert_eq!(
            result,
            "// Add returns the sum of two numbers.\n// \n// It panics on overflow.\n"
        );
    }

    #[test]
    fn test_format_java_single_line() {
        let result =
            format_doc_comment("Returns the sum of two numbers.", Language::Java, "", "add");
        assert_eq!(result, "/**\n * Returns the sum of two numbers.\n */\n");
    }

    #[test]
    fn test_format_java_multiline_with_indent() {
        let text = "Returns the sum.\n\n@param a first number\n@param b second number";
        let result = format_doc_comment(text, Language::Java, "    ", "add");
        let expected = "    /**\n     * Returns the sum.\n     * \n     * @param a first number\n     * @param b second number\n     */\n";
        assert_eq!(result, expected);
    }

    #[test]
    fn test_format_typescript_single_line() {
        let result = format_doc_comment(
            "Fetches data from the API.",
            Language::TypeScript,
            "",
            "fetchData",
        );
        assert_eq!(result, "/**\n * Fetches data from the API.\n */\n");
    }

    #[test]
    fn test_format_empty_text() {
        let result = format_doc_comment("", Language::Rust, "", "foo");
        assert_eq!(result, "");
    }

    #[test]
    fn test_format_default_language() {
        // Bash gets default // format
        let result = format_doc_comment("Runs the deploy script.", Language::Bash, "", "deploy");
        assert_eq!(result, "// Runs the deploy script.\n");
    }

    #[test]
    fn test_format_elixir() {
        let result =
            format_doc_comment("Adds two numbers together.", Language::Elixir, "  ", "add");
        assert_eq!(
            result,
            "  @doc \"\"\"\n  Adds two numbers together.\n  \"\"\"\n"
        );
    }

    #[test]
    fn test_format_ocaml() {
        let result =
            format_doc_comment("Computes the factorial.", Language::OCaml, "", "factorial");
        assert_eq!(result, "(** \nComputes the factorial.\n *)\n");
    }

    #[test]
    fn test_format_haskell() {
        let result = format_doc_comment(
            "Maps a function over a list.",
            Language::Haskell,
            "",
            "mapF",
        );
        assert_eq!(result, "-- | Maps a function over a list.\n");
    }

    #[test]
    fn test_format_ruby() {
        let result = format_doc_comment(
            "Initializes the connection pool.",
            Language::Ruby,
            "  ",
            "initialize",
        );
        assert_eq!(result, "  # Initializes the connection pool.\n");
    }

    #[test]
    fn all_language_doc_formats_are_valid() {
        // EX-36: Verify all language doc_format tags map to known formats.
        // A typo in a language definition would silently fall through to "default".
        let valid = [
            "triple_slash",
            "python_docstring",
            "go_comment",
            "javadoc",
            "hash_comment",
            "elixir_doc",
            "lua_ldoc",
            "haskell_haddock",
            "ocaml_doc",
            "erlang_edoc",
            "r_roxygen",
            "block_comment",
            "default",
        ];
        for lang in Language::all_variants() {
            if let Some(def) = lang.try_def() {
                assert!(
                    valid.contains(&def.doc_format),
                    "Language {:?} has unknown doc_format: {:?}",
                    lang,
                    def.doc_format
                );
            }
        }
    }

    #[test]
    fn test_block_comment_format() {
        let fmt = doc_format_from_tag("block_comment");
        assert_eq!(fmt.prefix, "(*");
        assert_eq!(fmt.line_prefix, "");
        assert_eq!(fmt.suffix, "*)");
        assert_eq!(fmt.position, InsertionPosition::BeforeFunction);
    }

    #[test]
    fn test_format_block_comment_single_line() {
        let fmt = doc_format_from_tag("block_comment");
        // Simulate format_doc_comment logic for block_comment
        let text = "Moves the axis to home position.";
        let indent = "  ";
        let mut result = String::new();
        result.push_str(indent);
        result.push_str(fmt.prefix);
        result.push('\n');
        for line in text.lines() {
            result.push_str(indent);
            result.push_str(fmt.line_prefix);
            result.push_str(line);
            result.push('\n');
        }
        result.push_str(indent);
        result.push_str(fmt.suffix);
        result.push('\n');
        assert_eq!(result, "  (*\n  Moves the axis to home position.\n  *)\n");
    }

    #[test]
    fn test_format_preserves_internal_indentation() {
        // Python text with its own indentation (e.g., Args section)
        let text = "Short summary.\n\nArgs:\n    x: The input value.";
        let result = format_doc_comment(text, Language::Rust, "", "foo");
        // Each line gets /// prefix; internal indentation is preserved
        assert_eq!(
            result,
            "/// Short summary.\n/// \n/// Args:\n///     x: The input value.\n"
        );
    }
}