1use std::collections::{BTreeSet, HashSet};
2
3use crate::language::{
4 DeclaredDep, DependencyManifestOwner, FlaggedLine, Function, LowerError, Manifest,
5 ManifestAnalysis, ReferenceRange, WorkspaceError,
6};
7
8#[cfg(test)]
9mod tests;
10
11pub trait ScanToken {
12 fn text(&self) -> &str;
13 fn is_keyword(&self, kw: &str) -> bool;
14 fn line(&self) -> u32;
15}
16
17fn delim_pair(open: &str) -> Option<(&'static str, &'static str)> {
18 match open {
19 "(" => Some(("(", ")")),
20 "{" => Some(("{", "}")),
21 "[" | "#[" => Some(("[", "]")),
22 _ => None,
23 }
24}
25
26pub fn find_matching_delim<T: ScanToken>(tokens: &[T], open_idx: usize) -> Option<usize> {
27 let (inc, dec) = delim_pair(tokens.get(open_idx)?.text())?;
28 let mut depth = 0usize;
29 for (idx, token) in tokens.iter().enumerate().skip(open_idx) {
30 let text = token.text();
31 if text == inc || (inc == "[" && text == "#[") {
32 depth += 1;
33 } else if text == dec {
34 depth -= 1;
35 if depth == 0 {
36 return Some(idx);
37 }
38 }
39 }
40 None
41}
42
43pub fn paren_then_brace<T: ScanToken>(
44 tokens: &[T],
45 kw_idx: usize,
46) -> Option<(usize, usize, usize, usize)> {
47 let paren_open = kw_idx + 1;
48 if tokens.get(paren_open)?.text() != "(" {
49 return None;
50 }
51 let paren_close = find_matching_delim(tokens, paren_open)?;
52 let brace_open = paren_close + 1;
53 if tokens.get(brace_open)?.text() != "{" {
54 return None;
55 }
56 let brace_close = find_matching_delim(tokens, brace_open)?;
57 Some((paren_open, paren_close, brace_open, brace_close))
58}
59
60pub fn flag_range(
61 start_line: u32,
62 end_line: u32,
63 rule: &'static str,
64 code_lines: &BTreeSet<u32>,
65 out: &mut BTreeSet<(u32, &'static str)>,
66) {
67 for &line in code_lines.range(start_line..=end_line) {
68 out.insert((line, rule));
69 }
70}
71
72pub fn finalize_flagged(flagged: BTreeSet<(u32, &'static str)>) -> Vec<FlaggedLine> {
73 flagged
74 .into_iter()
75 .map(|(line, rule)| FlaggedLine {
76 line,
77 rule: rule.to_owned(),
78 })
79 .collect()
80}
81
82pub fn check_c_style_if_else<T: ScanToken>(
83 tokens: &[T],
84 if_idx: usize,
85 exit_keywords: &[&str],
86 code_lines: &BTreeSet<u32>,
87 out: &mut BTreeSet<(u32, &'static str)>,
88) {
89 let Some((_, _, then_open, then_close)) = paren_then_brace(tokens, if_idx) else {
90 return;
91 };
92 let else_idx = then_close + 1;
93 if tokens.get(else_idx).is_none_or(|t| !t.is_keyword("else")) {
94 return;
95 }
96 let else_open = else_idx + 1;
97 if tokens.get(else_open).is_none_or(|t| t.text() != "{") {
98 return;
99 }
100 let Some(else_close) = find_matching_delim(tokens, else_open) else {
101 return;
102 };
103 let then_slice = &tokens[then_open + 1..then_close];
104 let else_slice = &tokens[else_open + 1..else_close];
105 if let (Some(a), Some(b)) = (
106 single_bool_return(then_slice),
107 single_bool_return(else_slice),
108 ) && a != b
109 {
110 flag_range(
111 tokens[if_idx].line(),
112 tokens[else_close].line(),
113 "if-else-returns-boolean",
114 code_lines,
115 out,
116 );
117 return;
118 }
119 if ends_with_unconditional_exit(then_slice, exit_keywords) {
120 flag_range(
121 tokens[else_idx].line(),
122 tokens[else_close].line(),
123 "else-after-return",
124 code_lines,
125 out,
126 );
127 }
128}
129
130fn single_bool_return<T: ScanToken>(slice: &[T]) -> Option<bool> {
131 if slice.len() == 3 && slice[0].is_keyword("return") && slice[2].text() == ";" {
132 if slice[1].is_keyword("true") {
133 Some(true)
134 } else if slice[1].is_keyword("false") {
135 Some(false)
136 } else {
137 None
138 }
139 } else {
140 None
141 }
142}
143
144fn ends_with_unconditional_exit<T: ScanToken>(slice: &[T], exit_keywords: &[&str]) -> bool {
145 if slice.last().is_none_or(|t| t.text() != ";") {
146 return false;
147 }
148 let mut depth = 0usize;
149 let mut stmt_start = 0usize;
150 for (idx, token) in slice.iter().enumerate() {
151 match token.text() {
152 "(" | "[" | "{" | "#[" => depth += 1,
153 ")" | "]" | "}" => depth = depth.saturating_sub(1),
154 ";" if depth == 0 && idx + 1 < slice.len() => stmt_start = idx + 1,
155 _ => {}
156 }
157 }
158 slice
159 .get(stmt_start)
160 .is_some_and(|t| exit_keywords.iter().any(|kw| t.is_keyword(kw)))
161}
162
163pub fn check_ternary_bool<T: ScanToken>(
164 tokens: &[T],
165 q_idx: usize,
166 code_lines: &BTreeSet<u32>,
167 out: &mut BTreeSet<(u32, &'static str)>,
168) {
169 if q_idx + 3 >= tokens.len() || tokens[q_idx + 2].text() != ":" {
170 return;
171 }
172 let a_true = tokens[q_idx + 1].is_keyword("true") && tokens[q_idx + 3].is_keyword("false");
173 let a_false = tokens[q_idx + 1].is_keyword("false") && tokens[q_idx + 3].is_keyword("true");
174 if a_true || a_false {
175 flag_range(
176 tokens[q_idx].line(),
177 tokens[q_idx + 3].line(),
178 "ternary-yields-boolean",
179 code_lines,
180 out,
181 );
182 }
183}
184
185pub fn score_function_spans<T: ScanToken>(
186 tokens: &[T],
187 code_lines: &BTreeSet<u32>,
188 spans: &[(usize, usize, u32, u32)],
189 decision_weight: impl Fn(&[T], usize) -> u32,
190) -> Vec<Function> {
191 let mut result: Vec<Function> = spans
192 .iter()
193 .enumerate()
194 .map(|(owner, &(body_start, body_end, start_line, end_line))| {
195 let mut decisions = 0u32;
196 let mut cursor = body_start;
197 while cursor <= body_end {
198 if let Some(child_end) = nested_end(spans, owner, cursor) {
199 cursor = child_end + 1;
200 continue;
201 }
202 decisions += decision_weight(tokens, cursor);
203 cursor += 1;
204 }
205 Function {
206 line: start_line,
207 end_line,
208 decision_points: decisions,
209 source_lines: code_lines.range(start_line..=end_line).count() as u32,
210 name: None,
211 cognitive_complexity: 0,
212 coverage: None,
213 }
214 })
215 .collect();
216 result.sort_by_key(|f| (f.line, f.end_line));
217 result
218}
219
220fn nested_end(spans: &[(usize, usize, u32, u32)], owner: usize, cursor: usize) -> Option<usize> {
221 spans
222 .iter()
223 .enumerate()
224 .find(|&(idx, &(start, _, _, _))| idx != owner && start == cursor)
225 .map(|(_, &(_, end, _, _))| end)
226}
227
228pub fn normalize_relative_path(base_dir: &str, rel: &str) -> Option<String> {
229 let mut segments: Vec<&str> = if base_dir.is_empty() {
230 Vec::new()
231 } else {
232 base_dir.split('/').collect()
233 };
234 for seg in rel.split('/') {
235 match seg {
236 "" | "." => {}
237 ".." => {
238 segments.pop()?;
239 }
240 other => segments.push(other),
241 }
242 }
243 Some(segments.join("/"))
244}
245
246pub fn find_manifests<P: AsRef<str>>(repository_paths: &[P], filename: &str) -> Vec<String> {
247 let nested = format!("/{filename}");
248 repository_paths
249 .iter()
250 .map(AsRef::as_ref)
251 .filter(|path| *path == filename || path.ends_with(&nested))
252 .map(str::to_owned)
253 .collect()
254}
255
256pub fn track_delim(stack: &mut Vec<(u8, u32)>, op: &str, line: u32) -> Result<(), LowerError> {
257 match op {
258 "#[" | "[" => stack.push((b'[', line)),
259 "{" => stack.push((b'{', line)),
260 "(" => stack.push((b'(', line)),
261 "}" | ")" | "]" => {
262 let expected = match op {
263 "}" => b'{',
264 ")" => b'(',
265 _ => b'[',
266 };
267 if !matches!(stack.pop(), Some((open, _)) if open == expected) {
268 return Err(LowerError::Unparsable(format!(
269 "unexpected {op:?} at line {line}"
270 )));
271 }
272 }
273 _ => {}
274 }
275 Ok(())
276}
277
278pub fn find_arrow_expr_end<T: ScanToken>(tokens: &[T], start: usize) -> usize {
279 let mut depth = 0usize;
280 for (idx, tok) in tokens.iter().enumerate().skip(start) {
281 match tok.text() {
282 "(" | "[" | "{" | "#[" => depth += 1,
283 ")" | "]" | "}" if depth == 0 => return idx.saturating_sub(1),
284 ")" | "]" | "}" => depth -= 1,
285 ";" | "," if depth == 0 => return idx.saturating_sub(1),
286 _ => {}
287 }
288 }
289 tokens.len().saturating_sub(1)
290}
291
292#[derive(Clone, Debug, PartialEq, Eq)]
293pub enum RelativeFileResolution {
294 Resolved(String),
295 Ignored,
296 Unresolved(String),
297}
298
299pub fn resolve_relative_file(
300 files: &HashSet<String>,
301 importer: &str,
302 rel_uri: &str,
303 ignore_vendor: bool,
304) -> RelativeFileResolution {
305 if rel_uri.starts_with('/') {
306 return RelativeFileResolution::Unresolved(format!(
307 "{rel_uri:?} is an absolute path, which depends on the machine"
308 ));
309 }
310 let parent = importer.rsplit_once('/').map_or("", |(dir, _)| dir);
311 let Some(joined) = normalize_relative_path(parent, rel_uri) else {
312 return RelativeFileResolution::Unresolved(format!(
313 "{rel_uri:?} leads outside the repository"
314 ));
315 };
316 if ignore_vendor && joined.split('/').any(|seg| seg == "vendor") {
317 return RelativeFileResolution::Ignored;
318 }
319 if files.contains(&joined) {
320 if joined == importer {
321 RelativeFileResolution::Ignored
322 } else {
323 RelativeFileResolution::Resolved(joined)
324 }
325 } else {
326 RelativeFileResolution::Unresolved(format!("no file of the repository matches {rel_uri:?}"))
327 }
328}
329
330pub const CALIBRATION_PROVENANCE: &str =
331 "ADR 0035, eval/panels.json, 2026-12-02, commit 9e3f53053618";
332
333pub fn calibrated_source(panel: &str) -> String {
334 format!("codeint stratified panel of {panel}, {CALIBRATION_PROVENANCE}")
335}
336
337pub struct CoreReferenceRanges {
338 pub erosion: (f64, f64),
339 pub cognitive_complexity: (f64, f64),
340 pub verbosity: (f64, f64),
341 pub duplication: (f64, f64),
342 pub import_cycles: Option<(f64, f64)>,
343}
344
345impl CoreReferenceRanges {
346 pub const fn new(
347 erosion: (f64, f64),
348 cognitive_complexity: (f64, f64),
349 verbosity: (f64, f64),
350 duplication: (f64, f64),
351 import_cycles: Option<(f64, f64)>,
352 ) -> Self {
353 Self {
354 erosion,
355 cognitive_complexity,
356 verbosity,
357 duplication,
358 import_cycles,
359 }
360 }
361
362 pub fn build(self, source: &str) -> Vec<ReferenceRange> {
363 let mut ranges = build_reference_ranges(
364 source,
365 [
366 ("erosion", 2, self.erosion.0, self.erosion.1),
367 (
368 "cognitive_complexity",
369 2,
370 self.cognitive_complexity.0,
371 self.cognitive_complexity.1,
372 ),
373 ("verbosity", 4, self.verbosity.0, self.verbosity.1),
374 ("duplication", 3, self.duplication.0, self.duplication.1),
375 ],
376 );
377 if let Some((low, high)) = self.import_cycles {
378 ranges.push(ReferenceRange {
379 metric: "import_cycles".to_owned(),
380 metric_version: 2,
381 low,
382 high,
383 source: source.to_owned(),
384 });
385 }
386 ranges
387 }
388}
389
390pub fn paths_with_suffix<'a, P: AsRef<str>>(
391 repository_paths: &'a [P],
392 suffix: &str,
393) -> HashSet<&'a str> {
394 repository_paths
395 .iter()
396 .map(AsRef::as_ref)
397 .filter(|path| path.ends_with(suffix))
398 .collect()
399}
400
401pub fn build_reference_ranges<const N: usize>(
402 source: &str,
403 entries: [(&str, u32, f64, f64); N],
404) -> Vec<ReferenceRange> {
405 entries
406 .into_iter()
407 .map(|(metric, metric_version, low, high)| ReferenceRange {
408 metric: metric.to_owned(),
409 metric_version,
410 low,
411 high,
412 source: source.to_owned(),
413 })
414 .collect()
415}
416
417pub fn manifest_root_excluding<'a>(
418 path: &'a str,
419 file_name: &str,
420 ignored_dirs: &[&str],
421) -> Option<&'a str> {
422 if path == file_name {
423 return Some("");
424 }
425 let dir = path.strip_suffix(file_name)?.strip_suffix('/')?;
426 (!dir.split('/').any(|seg| ignored_dirs.contains(&seg))).then_some(dir)
427}
428
429pub fn analyze_parsed_manifests<'a, Doc>(
430 manifests: &'a [Manifest],
431 root_manifest_path: &str,
432 parse_one: impl Fn(&'a Manifest) -> Option<Result<(String, Doc), WorkspaceError>>,
433 discover: impl FnOnce(
434 &'a [Manifest],
435 &[(String, String, Doc)],
436 ) -> Result<Vec<String>, WorkspaceError>,
437 include_owner: impl Fn(&Doc) -> bool,
438 extract_declared: impl FnOnce(&[(String, String, Doc)]) -> Vec<DeclaredDep>,
439) -> ManifestAnalysis {
440 let mut invalid_manifests = Vec::new();
441 let mut invalid_paths = HashSet::new();
442 let mut parsed = Vec::new();
443 for manifest in manifests {
444 let Some(result) = parse_one(manifest) else {
445 continue;
446 };
447 match result {
448 Ok((root, doc)) => parsed.push((root, manifest.path.clone(), doc)),
449 Err(error) => {
450 invalid_paths.insert(manifest.path.as_str());
451 invalid_manifests.push(error);
452 }
453 }
454 }
455 let workspace_packages = if !invalid_paths.contains(root_manifest_path)
456 && parsed.iter().any(|(_, path, _)| path == root_manifest_path)
457 {
458 match discover(manifests, &parsed) {
459 Ok(members) => members,
460 Err(error) => {
461 invalid_manifests.push(error);
462 parsed.retain(|(_, path, _)| path != root_manifest_path);
463 Vec::new()
464 }
465 }
466 } else {
467 Vec::new()
468 };
469 let dependency_manifests = parsed
470 .iter()
471 .filter(|(_, _, doc)| include_owner(doc))
472 .map(|(package_root, path, _)| DependencyManifestOwner {
473 package_root: package_root.clone(),
474 path: path.clone(),
475 })
476 .collect();
477 let declared_dependencies = extract_declared(&parsed);
478 ManifestAnalysis {
479 workspace_packages,
480 invalid_manifests,
481 dependency_manifests,
482 declared_dependencies,
483 manifest_used_dependencies: Vec::new(),
484 root_dependency_inheritance: Vec::new(),
485 }
486}