codingest 0.2.0

codingest — standalone extraction of KGLite's code-tree component: parse polyglot codebases into kglite knowledge graphs (tree-sitter parsers, call/type/route edges, docs pass, multi-rev merge)
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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
//! Shared parser helpers (ported from parsers/base.py).

use crate::models::{Annotation, FunctionInfo};
use aho_corasick::AhoCorasick;
use regex::Regex;
use serde_json::json;
use std::collections::HashSet;
use std::path::Path;
use std::sync::OnceLock;
use tree_sitter::Node;

// ── Closure-scoped definitions: naming (D2) ───────────────────────────
//
// Language-agnostic half of the nested-scope walk. The walk itself is
// per-grammar and lives in each parser, but what a nested definition is
// *called* — and how a duplicate is broken — has to be one implementation, or
// `parent_scope` would mean something subtly different per language and a
// cross-language query could not rely on it. Used by `typescript.rs`
// (Phase 3) and `python.rs` (Phase 4).

/// D2 qualified name: module path, then the chain of named enclosing scopes,
/// then the own name. An empty chain reproduces the pre-nesting top-level
/// shape `module.name` byte for byte.
pub fn scope_qualify(module_path: &str, chain: &[String], name: &str) -> String {
    let mut out = String::from(module_path);
    for segment in chain {
        out.push('.');
        out.push_str(segment);
    }
    out.push('.');
    out.push_str(name);
    out
}

/// Push `name` onto a named chain. A `None` chain stays `None`: D1's clause 5
/// refuses a node to anything below a scope the grammar cannot name.
pub fn extend_scope_chain(chain: Option<&[String]>, name: &str) -> Option<Vec<String>> {
    chain.map(|c| {
        let mut next = Vec::with_capacity(c.len() + 1);
        next.extend_from_slice(c);
        next.push(name.to_string());
        next
    })
}

/// Attach D2's two `Function` properties. Both are *absent* at top level
/// rather than written as empty/zero, so a build with no nested definitions
/// keeps its exact column set in `builder/load/entity_frames.rs`.
pub fn tag_scope(info: &mut FunctionInfo, module_path: &str, chain: &[String], depth: u32) {
    if let Some((own, head)) = chain.split_last() {
        info.metadata.insert(
            "parent_scope".into(),
            json!(scope_qualify(module_path, head, own)),
        );
    }
    if depth > 0 {
        info.metadata
            .insert("nesting_depth".into(), json!(u64::from(depth)));
    }
}

/// D2's duplicate-qualified-name tie-break.
///
/// A fully-named scope chain still collides when sibling blocks of one scope
/// declare the same name (4 sites in 10 374 opencode captures, e.g. two
/// `const scrub` in two branches of one function; in Python the `if`/`else`
/// and `try`/`except` conditional-definition idiom makes it routine). The
/// second and subsequent occurrences in a file, in source order, take a
/// `#{line}` suffix; the first keeps the bare name.
///
/// Deliberately *not* unconditional. Suffixing every qualified name would put
/// a line number into every CALLS target and every golden digest, so an edit
/// anywhere above a function would move its identity — the exact fragility
/// D2's amendment removed by dropping the `<anonL{line}>` marker. Only nested
/// definitions are ever rewritten: top-level and method qualified names are
/// the addressable public surface and a collision there predates the walk.
///
/// `functions` must be in source order, which is what every parser's walk
/// produces (a definition is emitted before the definitions inside it).
pub fn break_qualified_name_ties(functions: &mut [FunctionInfo]) {
    let mut seen: HashSet<String> = HashSet::with_capacity(functions.len());
    for function in functions.iter_mut() {
        if !seen.insert(function.qualified_name.clone()) {
            let nested = function
                .metadata
                .get("nesting_depth")
                .and_then(|v| v.as_u64())
                .is_some_and(|d| d > 0);
            if nested {
                function.qualified_name =
                    format!("{}#{}", function.qualified_name, function.line_number);
                seen.insert(function.qualified_name.clone());
            }
        }
    }
}

/// Build a module path from a file's location, joining the source-root
/// directory name, relative directory components, and file stem with
/// `separator` (`.` for Dart / Swift / HTML / CSS / JS / similar; `\` for
/// PHP namespace style).
///
/// Phase A.3 / 0.9.53 code-rot cleanup — consolidated from per-parser
/// copies in `dart.rs`, `html.rs`, `php.rs`, `swift.rs`, `css.rs`.
pub(super) fn file_to_module_path(filepath: &Path, src_root: &Path, separator: char) -> String {
    let stem = filepath.file_stem().and_then(|o| o.to_str()).unwrap_or("");
    let pkg = src_root.file_name().and_then(|o| o.to_str()).unwrap_or("");
    let mut parts = Vec::new();
    if !pkg.is_empty() {
        parts.push(pkg.to_string());
    }
    if let Ok(relative) = filepath.strip_prefix(src_root) {
        if let Some(parent) = relative.parent() {
            parts.extend(parent.components().filter_map(|component| {
                let value = component.as_os_str().to_str()?;
                (!value.is_empty()).then(|| value.to_string())
            }));
        }
    }
    if !stem.is_empty() {
        parts.push(stem.to_string());
    }
    parts.join(&separator.to_string())
}

/// Combine module path / owner prefix / name into a single qualified
/// identifier, joined with `separator` (`.` for most languages, `\` for
/// PHP). When an `owner_prefix` is present (e.g. an enclosing class /
/// struct / namespace), it wins over the module path — the owner is the
/// closer scope.
///
/// Phase A.3 / 0.9.53 code-rot cleanup — consolidated from
/// `dart.rs`, `php.rs`, `swift.rs`.
pub(super) fn make_qualified(
    module_path: &str,
    owner_prefix: &str,
    name: &str,
    separator: char,
) -> String {
    match (module_path.is_empty(), owner_prefix.is_empty()) {
        (true, true) => name.to_string(),
        (true, false) => format!("{owner_prefix}{separator}{name}"),
        (false, true) => format!("{module_path}{separator}{name}"),
        (false, false) => format!("{owner_prefix}{separator}{name}"),
    }
}

/// Fast byte-level filter: do any of the annotation keywords appear in
/// `source` at all? Built with aho-corasick (case-insensitive, no word
/// boundaries — accuracy is the regex's job; this is just a "skip the
/// AST walk entirely" precheck). Returns true on the first match.
fn has_annotation_keyword(source: &[u8]) -> bool {
    static AC: OnceLock<AhoCorasick> = OnceLock::new();
    let ac = AC.get_or_init(|| {
        AhoCorasick::builder()
            .ascii_case_insensitive(true)
            .build([
                "TODO", "FIXME", "HACK", "SAFETY", "XXX", "BUG", "NOTE", "WARNING",
            ])
            .expect("aho-corasick patterns compile")
    });
    ac.is_match(source)
}

/// Strict test-file detection shared across language parsers.
///
/// Returns true when the file is plausibly a test file. Two signals:
/// - `filename` ends with one of the language-specific `suffix_patterns`
///   (e.g. `.test.ts`, `Tests.swift`, `Test.php`).
/// - Any segment of `rel_path` is a conventional test directory:
///   `test`, `tests`, `__tests__`, `spec`, `specs`.
///
/// Path-segment-aware so we don't false-positive on names like
/// `latest.html`, `contest.css`, or `protest.swift` — the previous
/// `rel_path.to_lowercase().contains("test")` check did. Standard Go
/// (`*_test.go`) and Python (`test_*.py` / `*_test.py`) detection lives
/// inside their respective parsers because the conventions are specific
/// enough that this helper isn't a good fit.
pub fn is_test_path(rel_path: &str, filename: &str, suffix_patterns: &[&str]) -> bool {
    if suffix_patterns.iter().any(|s| filename.ends_with(s)) {
        return true;
    }
    let normalised = rel_path.replace('\\', "/");
    for segment in normalised.split('/') {
        if matches!(segment, "test" | "tests" | "__tests__" | "spec" | "specs") {
            return true;
        }
    }
    false
}

/// Extract the UTF-8 text of a tree-sitter node.
#[inline]
pub fn node_text<'a>(node: Node<'a>, source: &'a [u8]) -> &'a str {
    // UTF-8 boundaries are enforced by tree-sitter; safe unwrap on well-formed input.
    std::str::from_utf8(&source[node.byte_range()]).unwrap_or("")
}

/// Count lines of code in `source`. Matches the Python `count_lines` semantics:
/// number of newlines, plus one if the file is non-empty and doesn't end with `\n`.
pub fn count_lines(source: &[u8]) -> u32 {
    let newlines = bytecount_newlines(source);
    if !source.is_empty() && !source.ends_with(b"\n") {
        newlines + 1
    } else {
        newlines
    }
}

#[inline]
fn bytecount_newlines(src: &[u8]) -> u32 {
    src.iter().filter(|&&b| b == b'\n').count() as u32
}

/// Extract generic/template parameters from a declaration node.
///
/// Looks for a child whose type matches `node_type` (default: `"type_parameters"`)
/// and returns the inner text with surrounding `<>` or `[]` stripped.
pub fn get_type_parameters(node: Node, source: &[u8], node_type: &str) -> Option<String> {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == node_type {
            let text = node_text(child, source).trim();
            let stripped = if let Some(inner) =
                text.strip_prefix('<').and_then(|s| s.strip_suffix('>'))
            {
                inner.trim()
            } else if let Some(inner) = text.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
                inner.trim()
            } else {
                text
            };
            if stripped.is_empty() {
                return None;
            }
            return Some(stripped.to_string());
        }
    }
    None
}

fn annotation_regex() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(r"(?i)^(TODO|FIXME|HACK|SAFETY|XXX|BUG|NOTE|WARNING)\b[:\s]*(.*)")
            .expect("annotation regex compiles")
    })
}

/// Remove syntax decoration from one physical line of a comment node.
/// Repeated stripping handles doc/block combinations such as `/**`, `///`,
/// and the leading `*` on block-comment continuation lines.
fn comment_line_payload(mut line: &str) -> &str {
    line = line.trim();
    loop {
        let stripped = if let Some(rest) = line.strip_prefix("<!--") {
            rest
        } else if let Some(rest) = line.strip_prefix("/*") {
            rest
        } else if let Some(rest) = line.strip_prefix("//") {
            rest
        } else if let Some(rest) = line.strip_prefix('#') {
            rest
        } else if let Some(rest) = line.strip_prefix("--") {
            rest
        } else if let Some(rest) = line.strip_prefix(';') {
            rest
        } else if let Some(rest) = line.strip_prefix('*') {
            rest
        } else if let Some(rest) = line.strip_prefix('/') {
            rest
        } else if let Some(rest) = line.strip_prefix('!') {
            rest
        } else {
            break;
        };
        line = stripped.trim_start();
    }
    line = line.trim_end();
    for suffix in ["-->", "*/"] {
        if let Some(rest) = line.strip_suffix(suffix) {
            line = rest.trim_end();
            break;
        }
    }
    line
}

fn annotations_from_comment(text: &str, start_line: u32) -> Vec<Annotation> {
    let re = annotation_regex();
    text.lines()
        .enumerate()
        .filter_map(|(offset, line)| {
            let payload = comment_line_payload(line);
            let caps = re.captures(payload)?;
            let marker = caps.get(1)?;
            let marker_text = marker.as_str();
            let suffix = &payload[marker.end()..];
            if marker_text != marker_text.to_ascii_uppercase()
                && !suffix.trim_start().starts_with(':')
            {
                return None;
            }
            let kind = marker_text.to_ascii_uppercase();
            let body = caps.get(2).map(|m| m.as_str().trim()).unwrap_or("");
            Some(Annotation {
                kind,
                text: body.chars().take(200).collect(),
                line: start_line + offset as u32,
            })
        })
        .collect()
}

/// Default comment node kinds scanned by `extract_comment_annotations`.
pub const DEFAULT_COMMENT_TYPES: &[&str] = &["line_comment", "block_comment", "comment"];

/// Scan every comment node under `root` for TODO/FIXME/etc annotations.
///
/// Iterative stack traversal — avoids blowing Rust's call stack on deeply
/// nested ASTs (same reason the Python version uses an explicit stack).
///
/// Hot-path optimisation: the vast majority of files in real codebases
/// have no annotation keywords at all. A 64-bit byte-pattern pre-check
/// over the raw source skips the full AST walk in that case (which on
/// dotnet/runtime drops ~30% of the C# parse phase wall time).
pub fn extract_comment_annotations(
    root: Node,
    source: &[u8],
    comment_types: &[&str],
) -> Option<Vec<Annotation>> {
    if !has_annotation_keyword(source) {
        return None;
    }
    let mut out: Vec<Annotation> = Vec::new();
    let mut stack: Vec<Node> = vec![root];

    while let Some(node) = stack.pop() {
        let kind = node.kind();
        if comment_types.contains(&kind) {
            let text = node_text(node, source);
            out.extend(annotations_from_comment(
                text,
                node.start_position().row as u32 + 1,
            ));
        }
        // Push children in reverse so we pop them in source order.
        let mut cursor = node.walk();
        let children: Vec<Node> = node.children(&mut cursor).collect();
        for child in children.into_iter().rev() {
            stack.push(child);
        }
    }

    if out.is_empty() {
        None
    } else {
        Some(out)
    }
}

// ── Complexity counters (cyclomatic-style) ────────────────────────────

/// Branch-node kinds for each language's tree-sitter grammar.
///
/// These names are checked against `node.kind()` while walking a function body
/// to compute `branch_count` and `max_nesting`. Each entry adds 1 to the branch
/// count *and* contributes to nesting depth — so deeply nested `if`s and `for`s
/// surface a meaningful `max_nesting` value, while flat boolean chains
/// (`a && b && c`) only inflate `branch_count`.
///
/// Lists deliberately include short-circuit / ternary forms so the count
/// approximates McCabe cyclomatic complexity rather than just structural nesting.
pub const BRANCH_KINDS_PYTHON: &[&str] = &[
    "if_statement",
    "elif_clause",
    "while_statement",
    "for_statement",
    "except_clause",
    "case_clause",
    "conditional_expression", // ternary  a if c else b
    "boolean_operator",       // and / or
];

pub const BRANCH_KINDS_RUST: &[&str] = &[
    "if_expression",
    "while_expression",
    "while_let_expression",
    "for_expression",
    "loop_expression",
    "match_arm",
    "try_expression", // the `?` operator
];

pub const BRANCH_KINDS_GO: &[&str] = &[
    "if_statement",
    "for_statement",
    "expression_case",
    "type_case",
    "communication_case",
];

pub const BRANCH_KINDS_JAVA: &[&str] = &[
    "if_statement",
    "while_statement",
    "for_statement",
    "enhanced_for_statement",
    "do_statement",
    "switch_label",
    "catch_clause",
    "ternary_expression",
];

pub const BRANCH_KINDS_TS: &[&str] = &[
    "if_statement",
    "while_statement",
    "for_statement",
    "for_in_statement",
    "for_of_statement",
    "do_statement",
    "switch_case",
    "catch_clause",
    "ternary_expression",
];

pub const BRANCH_KINDS_CPP: &[&str] = &[
    "if_statement",
    "while_statement",
    "for_statement",
    "for_range_loop",
    "do_statement",
    "case_statement",
    "catch_clause",
    "conditional_expression",
];

pub const BRANCH_KINDS_CSHARP: &[&str] = &[
    "if_statement",
    "while_statement",
    "for_statement",
    "for_each_statement",
    "do_statement",
    "switch_section",
    "catch_clause",
    "conditional_expression",
];

pub const BRANCH_KINDS_DART: &[&str] = &[
    "if_statement",
    "while_statement",
    "for_statement",
    "do_statement",
    "switch_statement_case",
    "switch_expression_case",
    "catch_clause",
    "conditional_expression",
    "if_null_expression",
    "logical_and_expression",
    "logical_or_expression",
    "if_element",
    "for_element",
];

/// Walk `body` and return (branch_count, max_nesting).
///
/// `branch_count` increments for every node whose kind is in `branch_kinds`.
/// `max_nesting` is the deepest stack of nested `branch_kinds` nodes seen.
/// `nested_scope_kinds` (e.g. `function_definition`, `closure_expression`)
/// are NOT descended into — they belong to the caller's nested function/closure
/// and would inflate the outer function's metrics. Pass an empty slice if the
/// caller already filters those before invoking this helper.
pub fn compute_complexity(
    body: Node,
    branch_kinds: &[&str],
    nested_scope_kinds: &[&str],
) -> (u32, u32) {
    let branch_set: HashSet<&str> = branch_kinds.iter().copied().collect();
    let nested_set: HashSet<&str> = nested_scope_kinds.iter().copied().collect();
    let mut count: u32 = 0;
    let mut max_depth: u32 = 0;
    walk(
        body,
        &branch_set,
        &nested_set,
        0,
        &mut count,
        &mut max_depth,
    );
    (count, max_depth)
}

fn walk(
    node: Node,
    branches: &HashSet<&str>,
    nested: &HashSet<&str>,
    depth: u32,
    count: &mut u32,
    max_depth: &mut u32,
) {
    let kind = node.kind();
    let is_branch = branches.contains(kind);
    let next_depth = if is_branch {
        *count += 1;
        let d = depth + 1;
        if d > *max_depth {
            *max_depth = d;
        }
        d
    } else {
        depth
    };
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if nested.contains(child.kind()) {
            continue;
        }
        walk(child, branches, nested, next_depth, count, max_depth);
    }
}

// ── Macro decorator detection (C/C++) ─────────────────────────────────

/// Heuristic: does this token text look like a macro attribute/decorator
/// that the C/C++ parser should ignore when extracting names and types?
///
/// Matches all-uppercase identifiers with optional underscores/digits and
/// length ≥ 2: catches `SPDLOG_INLINE`, `FMT_API`, `FMT_BEGIN_NAMESPACE`,
/// `Q_INVOKABLE`, `BOOST_FOREACH`, `MOZ_ASSERT`, `__attribute__`-style names.
///
/// Excludes single-letter all-caps tokens (`T`, `K`, `N`) so generic template
/// parameter names aren't false-positives.
///
/// Used by `cpp.rs` to skip macro decorators in `get_return_type`, `get_name`,
/// and `extract_parameters` — without this, spdlog-style code like
/// `SPDLOG_INLINE void foo()` parses with `name="unknown"` and
/// `return_type="SPDLOG_INLINE"`.
pub fn looks_like_macro_decorator(text: &str) -> bool {
    if text.len() < 2 {
        return false;
    }
    let mut chars = text.chars();
    let first = chars.next().unwrap();
    if !(first.is_ascii_uppercase() || first == '_') {
        return false;
    }
    text.chars()
        .all(|c| c.is_ascii_uppercase() || c == '_' || c.is_ascii_digit())
}

// ── Procedure annotation extraction ───────────────────────────────────

fn procedure_annotation_regex() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        // Recognizes `@procedure: name`, `@procedure name`, `@cypher_procedure: name`
        // when they appear at the start of a line (with optional comment-prefix
        // whitespace). Anchored to line start so prose mentions like
        // "the @procedure: marker tells you..." don't false-positive.
        // Name is `[a-zA-Z_][a-zA-Z0-9_]*` (standard identifier).
        Regex::new(r"(?m)^\s*@(?:cypher_)?procedure[:\s]+([a-zA-Z_][a-zA-Z0-9_]*)")
            .expect("procedure annotation regex compiles")
    })
}

/// Extract all `@procedure: NAME` annotations from a docstring/leading comment
/// block. A single function can register under multiple procedure names via
/// repeated annotations — useful for aliases (e.g. both `betweenness` and
/// `betweenness_centrality` dispatching to the same impl).
///
/// Used to surface project-specific procedure registries (e.g. Cypher CALL
/// procedures, RPC method handlers, CLI subcommand dispatchers) as graph
/// `Procedure` nodes connected to their implementing Function.
pub fn extract_procedure_annotations(docstring: Option<&str>) -> Vec<String> {
    let Some(text) = docstring else {
        return Vec::new();
    };
    procedure_annotation_regex()
        .captures_iter(text)
        .filter_map(|c| c.get(1).map(|m| m.as_str().to_string()))
        .collect()
}

// ── Generated / minified file detection ───────────────────────────────

/// Codegen banner markers that — when found in a *comment line within the file's
/// first ~10 non-empty lines* — strongly indicate an auto-generated file.
///
/// Restricted to early comments (not anywhere in the first 2 KiB) so that doc
/// strings or test fixtures that happen to mention the words "auto-generated"
/// or "DO NOT EDIT" deeper in the file don't false-positive.
fn generated_marker_regex() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(concat!(
            r"(?i)(",
            // protoc, ts-proto, protoc-gen-go banners
            r"\bcode\s+generated\b",
            // Most codegen tools include this exact phrase, often uppercase
            r"|\bdo\s+not\s+edit\b",
            // bindgen, jOOQ, sqlc
            r"|\bautomatically\s+generated\b",
            // C# T4, Visual Studio designer files
            r"|<\s*auto-generated\s*>",
            // JSDoc / Flow / Cargo lockfile / Buck
            r"|@generated\b",
            // OpenAPI generator banner
            r"|\bgenerated\s+by\s+openapi",
            // generic "Generated by <tool>" — restrict to first 5 lines below
            r"|^\s*(?://|#|/\*|\*|--|<!--)\s*Generated\s+by\b",
            r")",
        ))
        .expect("generated marker regex compiles")
    })
}

/// Returns true if the line looks like a comment (starts with a comment
/// delimiter for one of the supported languages).
fn is_comment_line(line: &str) -> bool {
    let t = line.trim_start();
    t.starts_with("//")
        || t.starts_with('#')
        || t.starts_with("/*")
        || t.starts_with('*')
        || t.starts_with("--")
        || t.starts_with("<!--")
        || t.starts_with(';')
}

/// Detect generated or minified source files by content sniff.
///
/// Returns `Some("generated")` if any of the file's first ~10 non-empty lines
/// is a comment containing a codegen banner marker (e.g. `// Code generated by
/// protoc; DO NOT EDIT.`, `# @generated`, `<auto-generated>`). Restricting the
/// scan to early *comment* lines avoids false-positives on doc strings or test
/// fixtures that quote the same phrases deeper in a hand-written file.
///
/// Returns `Some("minified")` if the file is one extremely long line, or its
/// average non-empty-line width across the first 50 lines exceeds 500 chars
/// (catches webpack/rollup-bundled JS).
///
/// Returns `None` for normal hand-written source.
///
/// Designed to run BEFORE the tree-sitter parse — these files would otherwise
/// inflate the graph with phantom CALLS edges or single-blob "function" nodes
/// that mask real code structure.
pub fn is_generated_or_minified(source: &[u8]) -> Option<&'static str> {
    if source.is_empty() {
        return None;
    }

    // Banner check: scan up to the first 10 non-empty lines, only test the regex
    // against lines that look like comments. Codegen banners always live at
    // the very top of the file inside a comment block.
    let head_len = source.len().min(4096);
    let head = &source[..head_len];
    let head_str = match std::str::from_utf8(head) {
        Ok(text) => text,
        Err(error) => std::str::from_utf8(&head[..error.valid_up_to()]).unwrap_or(""),
    };
    let re = generated_marker_regex();
    let mut non_empty_seen = 0;
    for line in head_str.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        non_empty_seen += 1;
        if non_empty_seen > 10 {
            break;
        }
        if is_comment_line(line) && re.is_match(line) {
            return Some("generated");
        }
    }

    // Minified: one huge line, OR average line width above threshold across
    // the first 50 non-empty lines.
    if source.len() >= 1024 {
        let newline_count = source.iter().filter(|&&b| b == b'\n').count();
        if newline_count == 0 {
            return Some("minified");
        }
    }
    let mut lines_seen: u32 = 0;
    let mut total_width: u64 = 0;
    for raw_line in source.split(|&b| b == b'\n') {
        if raw_line.is_empty() {
            continue;
        }
        total_width += raw_line.len() as u64;
        lines_seen += 1;
        if lines_seen >= 50 {
            break;
        }
    }
    if lines_seen >= 5 {
        let avg = total_width / lines_seen as u64;
        if avg > 500 {
            return Some("minified");
        }
    }

    None
}

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

    #[test]
    fn annotations_require_a_leading_marker_and_keep_physical_lines() {
        let comment = "/* This fixes a bug class.\n * TODO: wire the cache\n * warning users is ordinary prose\n * FIXME second item\n */";
        let annotations = annotations_from_comment(comment, 20);
        assert_eq!(annotations.len(), 2);
        assert_eq!(annotations[0].kind, "TODO");
        assert_eq!(annotations[0].text, "wire the cache");
        assert_eq!(annotations[0].line, 21);
        assert_eq!(annotations[1].kind, "FIXME");
        assert_eq!(annotations[1].text, "second item");
        assert_eq!(annotations[1].line, 23);
    }

    #[test]
    fn annotations_support_common_comment_decorators_in_source_order() {
        let comment = "/// NOTE: first\n//! SAFETY second\n<!-- HACK: third -->";
        let annotations = annotations_from_comment(comment, 7);
        let actual: Vec<(&str, &str, u32)> = annotations
            .iter()
            .map(|a| (a.kind.as_str(), a.text.as_str(), a.line))
            .collect();
        assert_eq!(
            actual,
            vec![
                ("NOTE", "first", 7),
                ("SAFETY", "second", 8),
                ("HACK", "third", 9),
            ]
        );
    }

    #[test]
    fn generated_banner_survives_a_split_utf8_boundary() {
        let mut source = b"// Code generated by fixture; DO NOT EDIT.\n".to_vec();
        source.resize(4095, b'a');
        source.extend_from_slice("é".as_bytes());
        source.push(b'\n');
        assert_eq!(is_generated_or_minified(&source), Some("generated"));
    }

    #[test]
    fn fallback_module_paths_keep_relative_directories_and_top_level_shape() {
        let root = Path::new("/repo/site");
        assert_eq!(
            file_to_module_path(Path::new("/repo/site/index.html"), root, '.'),
            "site.index"
        );
        assert_eq!(
            file_to_module_path(Path::new("/repo/site/pages/index.html"), root, '.'),
            "site.pages.index"
        );
        assert_eq!(
            file_to_module_path(Path::new("/repo/site/pages/index.php"), root, '\\'),
            "site\\pages\\index"
        );
    }
}