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};
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)
}
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()))?;
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);
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)
}
const MAX_SOURCE_BYTES: usize = 4 * 1024 * 1024;
const GENERATED_HEADER_BYTES: usize = 2048;
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
}
}
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)
}
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,
}
}
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
}
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}\\"))
})
}
fn looks_like_cpp(src: &str) -> bool {
use regex::Regex;
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;
}
if src.contains("::") {
return true;
}
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
}
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
}
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)
}
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 {
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
}
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>,
}
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
);
assert_eq!(
generated_file_marker("// Code generated lazily at runtime\npackage x"),
None
);
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() {
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);
}
}