hotspots-core 3.4.1

Core library for finding the riskiest code by combining complexity with git change history (Local Risk Score) across TypeScript, JavaScript, Go, Python, Rust, Java, C#, and C
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
//! Analysis orchestration - ties together parsing, discovery, CFG, metrics, and reporting

use crate::ast::FunctionNode;
use crate::language::{self, Language, LanguageParser};
use crate::metrics;
use crate::report;
use crate::risk;
use anyhow::{Context, Result};
use std::panic::{self, AssertUnwindSafe};
use std::path::Path;
use swc_common::{sync::Lrc, SourceMap};

/// Analyze a source file (TypeScript, JavaScript, Go, or Rust)
pub fn analyze_file(
    path: &Path,
    source_map: &Lrc<SourceMap>,
    file_index: usize,
    options: &crate::AnalysisOptions,
) -> Result<Vec<report::FunctionRiskReport>> {
    analyze_file_with_config(path, source_map, file_index, options, None, None)
}

/// Analyze a file with optional custom weights and thresholds
pub fn analyze_file_with_config(
    path: &Path,
    source_map: &Lrc<SourceMap>,
    file_index: usize,
    options: &crate::AnalysisOptions,
    weights: Option<&risk::LrsWeights>,
    thresholds: Option<&risk::RiskThresholds>,
) -> Result<Vec<report::FunctionRiskReport>> {
    let default_weights = risk::LrsWeights::default();
    let default_thresholds = risk::RiskThresholds::default();
    let w = weights.unwrap_or(&default_weights);
    let t = thresholds.unwrap_or(&default_thresholds);

    let src = std::fs::read_to_string(path)
        .with_context(|| format!("Failed to read file: {}", path.display()))?;

    if src.len() > MAX_SOURCE_BYTES {
        eprintln!(
            "warning: skipping {} — file is {} MiB (limit {} MiB); likely generated",
            path.display(),
            src.len() / (1024 * 1024),
            MAX_SOURCE_BYTES / (1024 * 1024)
        );
        return Ok(vec![]);
    }
    if let Some(marker) = generated_file_marker(&src) {
        eprintln!(
            "warning: skipping {} — header marks it as generated code ({})",
            path.display(),
            marker
        );
        return Ok(vec![]);
    }

    let (max_line, long_line_count) = long_line_stats(&src, 1000);
    if long_line_count >= 3 {
        eprintln!(
            "warning: skipping {} — looks minified or machine-generated \
             ({} lines exceed 1000 chars, max: {})",
            path.display(),
            long_line_count,
            max_line
        );
        return Ok(vec![]);
    } else if looks_vendored(path) {
        eprintln!(
            "warning: skipping {} — path suggests vendored or generated third-party code",
            path.display()
        );
        return Ok(vec![]);
    }

    let mut language = Language::from_path(path)
        .ok_or_else(|| anyhow::anyhow!("Unsupported file type: {}", path.display()))?;

    // `.h` is ambiguous: a header that uses C++ syntax goes to the C++ grammar instead
    // of the C one, which would drop or mis-parse its member functions (issue #204).
    if language == Language::CHeader {
        language = choose_header_language(&src);
    }

    if let Some(limit) = nesting_limit(language) {
        let depth = max_bracket_depth(&src, limit);
        if depth > limit {
            eprintln!(
                "warning: skipping {} — nesting is deeper than {} levels, which can overflow the stack \
                 in the {} parser",
                path.display(),
                limit,
                language.name()
            );
            return Ok(vec![]);
        }
    }

    let parser = create_parser(language, source_map)?;

    let parse_result = panic::catch_unwind(AssertUnwindSafe(|| {
        parser.parse(&src, &path.to_string_lossy())
    }));

    let module = match parse_result {
        Ok(result) => result?,
        Err(panic_payload) => {
            let msg = panic_payload
                .downcast_ref::<&str>()
                .map(|s| s.to_string())
                .or_else(|| panic_payload.downcast_ref::<String>().cloned())
                .unwrap_or_else(|| "unknown panic".to_string());
            eprintln!(
                "warning: skipping {} — parser panicked: {}",
                path.display(),
                msg
            );
            return Ok(vec![]);
        }
    };
    let mut functions = module.discover_functions(file_index, &src);

    // Extract suppression comments here, uniformly across all languages —
    // language-specific parsers leave `suppression_reason: None` and rely on
    // this pass rather than each duplicating the (language-agnostic) logic.
    let comment_prefix = language.suppression_comment_prefix();
    let line_starts = crate::suppression::line_starts(&src);
    for function in &mut functions {
        function.suppression_reason = crate::suppression::extract_suppression_indexed(
            &src,
            &line_starts,
            function.span,
            comment_prefix,
        );
    }

    let func_cfg = FunctionAnalysisConfig {
        options,
        weights: w,
        thresholds: t,
        source_map,
    };
    let mut reports = Vec::new();
    for function in &functions {
        if let Some(report) = analyze_function(function, path, language, &func_cfg) {
            reports.push(report);
        }
    }
    Ok(reports)
}

/// Source files larger than this are skipped. Real hand-written files are far smaller; the cases
/// above this are generated code (e.g. a 12 MB Thrift-generated Java file took the analyzer to
/// ~120 GB resident and made a whole-repo run time out).
const MAX_SOURCE_BYTES: usize = 4 * 1024 * 1024;

/// How much of a file's start is searched for a "generated" marker.
const GENERATED_HEADER_BYTES: usize = 2048;

/// Returns the marker found if the file's header says it is generated code that humans don't author:
/// `@generated`, `Autogenerated by ...` (Thrift and others), or Go's `Code generated ... DO NOT EDIT`.
fn generated_file_marker(src: &str) -> Option<&'static str> {
    let mut end = src.len().min(GENERATED_HEADER_BYTES);
    while !src.is_char_boundary(end) {
        end -= 1;
    }
    let header = &src[..end];
    if header.contains("@generated") {
        Some("@generated")
    } else if header.contains("Autogenerated by") {
        Some("Autogenerated by")
    } else if header.contains("Code generated") && header.contains("DO NOT EDIT") {
        Some("Code generated ... DO NOT EDIT")
    } else {
        None
    }
}

/// Returns the length of the longest line and the count of lines exceeding `threshold` chars.
///
/// Used to detect minified or machine-generated files before full analysis.
fn long_line_stats(src: &str, threshold: usize) -> (usize, usize) {
    let mut max_len = 0;
    let mut count = 0;
    for line in src.lines() {
        let len = line.len();
        if len > max_len {
            max_len = len;
        }
        if len > threshold {
            count += 1;
        }
    }
    (max_len, count)
}

/// Bracket-nesting depth beyond which a language's parser can overflow its thread stack.
///
/// The Rust (`syn`) and ECMAScript (`swc`) parsers are recursive descent and Go's later stages
/// recurse too; none of that is ours to make iterative. Measured on the 32 MiB worker stacks the
/// CLI uses, overflow starts near 1,600 nested blocks for Rust, 2,600 nested parentheses for
/// TypeScript and 11,000 nested blocks for Go. These limits sit well below those, and far above
/// anything hand-written. This is a mitigation, not a fix: a single expression with tens of
/// thousands of operators and no brackets can still overflow.
fn nesting_limit(language: Language) -> Option<usize> {
    match language {
        Language::Rust => Some(1_000),
        Language::TypeScript
        | Language::TypeScriptReact
        | Language::JavaScript
        | Language::JavaScriptReact
        | Language::Vue
        | Language::Astro => Some(1_500),
        Language::Go => Some(5_000),
        _ => None,
    }
}

/// Maximum nesting of `()`, `[]` and `{}` in `src`, stopping as soon as it exceeds `stop_after`.
///
/// A plain byte scan that ignores strings and comments: brackets inside them can only raise the
/// count, which errs towards skipping a file, never towards a crash. Unmatched closers do not
/// drive the depth negative.
fn max_bracket_depth(src: &str, stop_after: usize) -> usize {
    let mut depth = 0usize;
    let mut max = 0usize;
    for b in src.bytes() {
        match b {
            b'(' | b'[' | b'{' => {
                depth += 1;
                if depth > max {
                    max = depth;
                    if max > stop_after {
                        return max;
                    }
                }
            }
            b')' | b']' | b'}' => depth = depth.saturating_sub(1),
            _ => {}
        }
    }
    max
}

/// Returns true if a file path suggests it contains vendored or generated third-party code.
///
/// Checks for common directory conventions used to store vendor dependencies, static assets,
/// and generated files that are typically not authored code (e.g. `vendor/`, `assets/js/`,
/// `third_party/`, `fixtures/`).
fn looks_vendored(path: &Path) -> bool {
    const VENDORED_SEGMENTS: &[&str] = &[
        "vendor",
        "vendors",
        "third_party",
        "thirdparty",
        "assets/js",
        "static/js",
        "public/js",
        "dist/js",
    ];
    let path_str = path.to_string_lossy().to_lowercase();
    VENDORED_SEGMENTS.iter().any(|seg| {
        path_str.contains(&format!("/{seg}/")) || path_str.contains(&format!("/{seg}\\"))
    })
}

/// Returns true if the content of a `.h` file looks like C++ rather than C.
///
/// `.h` files default to the C grammar (`Language::CHeader`), but a large
/// share of `.h` files in C++ projects are actually C++ (member functions, templates,
/// range-based `for`, `namespace`, `::`-qualified names). The C grammar either drops
/// those constructs silently or produces a confusing "invalid CFG" error (see issue
/// #204), so such files are detected here and parsed as C++ instead.
fn looks_like_cpp(src: &str) -> bool {
    use regex::Regex;

    // Judge the code, not the prose: `size class` in a comment or `"a::b"` in a string is not C++.
    let stripped = strip_comments_and_strings(src);
    let src = stripped.as_str();

    const KEYWORD_MARKERS: &[&str] = &[
        "class ",
        "template<",
        "template <",
        "namespace ",
        "public:",
        "private:",
        "protected:",
    ];
    if KEYWORD_MARKERS.iter().any(|kw| src.contains(kw)) {
        return true;
    }

    // `::`-qualified names (e.g. `std::vector`, `Foo::bar`) are not valid C.
    if src.contains("::") {
        return true;
    }

    // Range-based for loop: `for (... : ...)` — not recognized by the C grammar,
    // which is why a `break` inside one has no enclosing loop target (issue #204).
    static RANGE_FOR_RE: std::sync::OnceLock<Regex> = std::sync::OnceLock::new();
    let range_for_re =
        RANGE_FOR_RE.get_or_init(|| Regex::new(r"for\s*\([^;()]*:[^;()]*\)").unwrap());
    if range_for_re.is_match(src) {
        return true;
    }

    false
}

/// Decides whether a `.h` file is C or C++.
///
/// 1. The marker heuristic (`looks_like_cpp`: `class `, `namespace `, `::`, range-for, ...) runs on the
///    code only, with comments and string literals blanked, so a C header that says "size class" in a
///    comment is not sent to the C++ grammar (which mis-parses C idioms such as an identifier `new`).
/// 2. If the markers say C but the C grammar reports errors and the C++ grammar parses the file
///    cleanly, it is C++ without any marker (references, `constexpr`, `auto`, default arguments).
///
/// A clean C parse is deliberately not treated as proof of C: tree-sitter-c reads `namespace x { ... }`
/// as a function-like definition without errors. Comparing raw error counts was tried and rejected:
/// it moved large, macro-heavy C++ headers to the C parser, which then found fewer functions.
pub(crate) fn choose_header_language(src: &str) -> Language {
    if looks_like_cpp(src) {
        return Language::Cpp;
    }
    let c_has_errors =
        parse_error_count(tree_sitter_c::LANGUAGE.into(), src).is_some_and(|n| n > 0);
    if c_has_errors && parse_error_count(tree_sitter_cpp::LANGUAGE.into(), src) == Some(0) {
        return Language::Cpp;
    }
    Language::CHeader
}

/// Number of ERROR and MISSING nodes tree-sitter produces for `src`, or None if parsing fails or
/// takes more than 5 s. Iterative, and descends only into subtrees that contain an error.
fn parse_error_count(language: tree_sitter::Language, src: &str) -> Option<usize> {
    let mut parser = tree_sitter::Parser::new();
    parser.set_language(&language).ok()?;
    let start = std::time::Instant::now();
    let mut cancel =
        |_: &tree_sitter::ParseState| start.elapsed() > std::time::Duration::from_secs(5);
    let options = tree_sitter::ParseOptions::new().progress_callback(&mut cancel);
    let bytes = src.as_bytes();
    let tree = parser.parse_with_options(
        &mut |offset, _| bytes.get(offset..).unwrap_or(&[]),
        None,
        Some(options),
    )?;
    let mut count = 0;
    let mut stack = vec![tree.root_node()];
    while let Some(node) = stack.pop() {
        if !node.has_error() {
            continue;
        }
        if node.is_error() || node.is_missing() {
            count += 1;
        }
        let mut cursor = node.walk();
        stack.extend(node.children(&mut cursor));
    }
    Some(count)
}

/// Replaces the contents of C-family comments and string/char literals with spaces (newlines kept),
/// so keyword checks see only code. Not a full lexer: it handles `//`, `/* */`, `"..."` and `'...'`
/// with backslash escapes, which is enough for header classification.
fn strip_comments_and_strings(src: &str) -> String {
    let bytes = src.as_bytes();
    let mut out = String::with_capacity(src.len());
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        if b == b'/' && bytes.get(i + 1) == Some(&b'/') {
            while i < bytes.len() && bytes[i] != b'\n' {
                i += 1;
            }
        } else if b == b'/' && bytes.get(i + 1) == Some(&b'*') {
            i += 2;
            while i < bytes.len() && !(bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/')) {
                if bytes[i] == b'\n' {
                    out.push('\n');
                }
                i += 1;
            }
            i = (i + 2).min(bytes.len());
            out.push(' ');
        } else if b == b'"' || b == b'\'' {
            let quote = b;
            i += 1;
            while i < bytes.len() && bytes[i] != quote && bytes[i] != b'\n' {
                if bytes[i] == b'\\' {
                    i += 1;
                }
                i += 1;
            }
            i += 1;
            out.push(' ');
        } else {
            // Copy one whole UTF-8 character.
            let ch_len = src[i..].chars().next().map_or(1, char::len_utf8);
            out.push_str(&src[i..i + ch_len]);
            i += ch_len;
        }
    }
    out
}

/// Instantiates the correct parser for the given language.
fn create_parser(
    language: Language,
    source_map: &Lrc<SourceMap>,
) -> Result<Box<dyn LanguageParser>> {
    let parser: Box<dyn LanguageParser> = match language {
        Language::TypeScript
        | Language::TypeScriptReact
        | Language::JavaScript
        | Language::JavaScriptReact => {
            Box::new(language::ECMAScriptParser::new(source_map.clone()))
        }
        Language::Go => Box::new(language::GoParser::new().context("Failed to create Go parser")?),
        Language::Java => {
            Box::new(language::JavaParser::new().context("Failed to create Java parser")?)
        }
        Language::Python => {
            Box::new(language::PythonParser::new().context("Failed to create Python parser")?)
        }
        Language::Rust => Box::new(language::RustParser),
        Language::Vue => Box::new(language::VueParser::new(source_map.clone())),
        Language::Astro => Box::new(language::AstroParser::new(source_map.clone())),
        Language::CSharp => {
            Box::new(language::CSharpParser::new().context("Failed to create C# parser")?)
        }
        Language::C | Language::CHeader => {
            Box::new(language::CParser::new().context("Failed to create C parser")?)
        }
        Language::Cpp => {
            Box::new(language::CppParser::new().context("Failed to create C++ parser")?)
        }
        Language::Php => {
            Box::new(language::PhpParser::new().context("Failed to create PHP parser")?)
        }
    };
    Ok(parser)
}

struct FunctionAnalysisConfig<'a> {
    options: &'a crate::AnalysisOptions,
    weights: &'a risk::LrsWeights,
    thresholds: &'a risk::RiskThresholds,
    source_map: &'a Lrc<SourceMap>,
}

/// Builds CFG, extracts metrics, computes risk for one function.
/// Returns None if the CFG is invalid or the function is filtered by min_lrs.
fn analyze_function(
    function: &FunctionNode,
    path: &Path,
    language: Language,
    config: &FunctionAnalysisConfig<'_>,
) -> Option<report::FunctionRiskReport> {
    let w = config.weights;
    let t = config.thresholds;
    let options = config.options;
    let source_map = config.source_map;

    let cfg = language::get_builder_for_function(function).build(function);
    let cfg_valid = cfg.validate();
    if let Err(e) = cfg_valid {
        eprintln!(
            "warning: skipping function '{}' in {}: invalid CFG: {}",
            function.name.as_deref().unwrap_or("<anonymous>"),
            path.display(),
            e
        );
        return None;
    }

    let raw_metrics = metrics::extract_metrics(function, &cfg);

    let (risk_components, lrs, band) = risk::analyze_risk_with_config(&raw_metrics, w, t);

    if options.min_lrs.is_some_and(|min| lrs < min) {
        return None;
    }

    Some(report::FunctionRiskReport::new(
        function,
        path.to_string_lossy().to_string(),
        language,
        report::FunctionAnalysis {
            metrics: raw_metrics,
            risk: risk_components,
            lrs,
            band,
        },
        source_map,
    ))
}

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

    #[test]
    fn generated_header_markers_are_detected() {
        assert_eq!(
            generated_file_marker(
                "/**\n * Autogenerated by Thrift Compiler (0.16.0)\n */\nclass A {}"
            ),
            Some("Autogenerated by")
        );
        assert_eq!(
            generated_file_marker("// @generated by tool\nfn x() {}"),
            Some("@generated")
        );
        assert_eq!(
            generated_file_marker("// Code generated by protoc-gen-go. DO NOT EDIT.\npackage x"),
            Some("Code generated ... DO NOT EDIT")
        );
    }

    #[test]
    fn ordinary_files_are_not_marked_generated() {
        assert_eq!(
            generated_file_marker("package main\nfunc main() {}\n"),
            None
        );
        // "Code generated" alone (no DO NOT EDIT) is not enough
        assert_eq!(
            generated_file_marker("// Code generated lazily at runtime\npackage x"),
            None
        );
        // a marker far past the header is ignored
        let late = format!("{}// @generated\n", "x\n".repeat(2000));
        assert_eq!(generated_file_marker(&late), None);
    }

    #[test]
    fn header_scan_does_not_split_multibyte_chars() {
        let src = "é".repeat(GENERATED_HEADER_BYTES);
        assert_eq!(generated_file_marker(&src), None);
    }

    #[test]
    fn max_bracket_depth_counts_nesting_and_stops_early() {
        assert_eq!(max_bracket_depth("fn f() { if x { (1) } }", 100), 3);
        assert_eq!(max_bracket_depth("}}}{", 100), 1);
        let deep = "{".repeat(5000);
        assert!(max_bracket_depth(&deep, 100) > 100);
    }

    #[test]
    fn nesting_limits_cover_the_recursive_parsers() {
        assert!(nesting_limit(Language::Rust).is_some());
        assert!(nesting_limit(Language::TypeScript).is_some());
        assert!(nesting_limit(Language::Go).is_some());
        assert!(nesting_limit(Language::Java).is_none());
    }

    #[test]
    fn header_words_in_comments_and_strings_do_not_make_it_cpp() {
        let c = "/* size class lookup, see std::vector in the docs */\n\
                 // namespace of the module: class table\n\
                 static const char *msg = \"a::b class namespace \";\n\
                 static inline int add(int a, int b) { return a + b; }\n";
        assert_eq!(choose_header_language(c), Language::CHeader);
    }

    #[test]
    fn header_with_cpp_in_code_is_cpp() {
        let cpp = "namespace app { class Foo { public: int get() const { return 1; } }; }\n";
        assert_eq!(choose_header_language(cpp), Language::Cpp);
        let range_for =
            "inline int sum(int n) { int t = 0; for (int x : v) { t += x; } return t; }\n";
        assert_eq!(choose_header_language(range_for), Language::Cpp);
    }

    #[test]
    fn markerless_cpp_header_is_detected_by_parse() {
        // References and constexpr are not valid C and none of the keyword markers appear.
        let cpp = "constexpr int kMax = 5;\nint twice(const int& x);\n";
        assert_eq!(choose_header_language(cpp), Language::Cpp);
    }

    #[test]
    fn plain_c_header_stays_c() {
        let c = "#ifndef X_H\n#define X_H\ntypedef struct { int a; } S;\nint f(S *s);\n#endif\n";
        assert_eq!(choose_header_language(c), Language::CHeader);
    }

    #[test]
    fn strip_blanks_comments_and_strings_but_keeps_code_and_lines() {
        let out =
            strip_comments_and_strings("int a; // class\n/* ns:: */ char *s = \"::\\\"x\"; 'c'\n");
        assert!(!out.contains("class") && !out.contains("::"));
        assert!(out.contains("int a;") && out.contains("char *s ="));
        assert_eq!(out.matches('\n').count(), 2);
    }
}