Skip to main content

fallow_engine/health/
inline.rs

1//! Complexity signals for editors, from the same threshold rule as
2//! `fallow health`.
3
4use std::path::PathBuf;
5
6use fallow_config::{ResolvedConfig, Severity};
7use fallow_types::discover::DiscoveredFile;
8
9use super::threshold_overrides::{GlobalHealthThresholds, ThresholdOverrideResolver};
10use crate::source::ModuleInfo;
11
12/// One function above a complexity threshold, for an editor code lens.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct InlineComplexity {
15    /// Absolute path of the file that declares the function.
16    pub path: PathBuf,
17    /// Function name as extracted from the source.
18    pub name: String,
19    /// One-based line of the function declaration.
20    pub line: u32,
21    /// Zero-based column of the function declaration.
22    pub col: u32,
23    /// Cyclomatic complexity as the gate reads it under
24    /// `health.cyclomaticPolicy`.
25    pub cyclomatic: u16,
26    /// Measured cognitive complexity.
27    pub cognitive: u16,
28    /// The function is above the effective cyclomatic threshold.
29    pub exceeds_cyclomatic: bool,
30    /// The function is above the effective cognitive threshold.
31    pub exceeds_cognitive: bool,
32}
33
34/// The functions of the parsed modules that are above a complexity threshold.
35///
36/// This applies the rules of the `fallow health` findings: `health.ignore`,
37/// the `complexity` suppression comments, the module-scope unit that never
38/// becomes a finding, and the effective thresholds of `health.thresholdOverrides`
39/// per file and function. It also applies the `complexity-cyclomatic` and
40/// `complexity-cognitive` rules with `overrides[].rules` for the file: a
41/// function whose cyclomatic and cognitive kinds are all `off` is dropped.
42///
43/// A lens covers only the cyclomatic and cognitive kinds. It has no CRAP
44/// score, so `complexity-crap` has no effect here. A function that the health
45/// report flags only through CRAP, or whose cyclomatic and cognitive rules are
46/// `off` while its CRAP rule is on, has a health finding but no lens.
47#[must_use]
48pub fn inline_complexity(
49    config: &ResolvedConfig,
50    modules: &[ModuleInfo],
51    files: &[DiscoveredFile],
52) -> Vec<InlineComplexity> {
53    let file_paths: rustc_hash::FxHashMap<_, _> =
54        files.iter().map(|file| (file.id, &file.path)).collect();
55    let ignore_set = super::ignore::build_ignore_set(&config.health.ignore);
56    let resolver = ThresholdOverrideResolver::new(
57        &config.health.threshold_overrides,
58        GlobalHealthThresholds {
59            cyclomatic: config.health.max_cyclomatic,
60            cognitive: config.health.max_cognitive,
61            crap: config.health.max_crap,
62            unit_size: config.health.max_unit_size,
63        },
64    )
65    .with_cyclomatic_policy(config.health.cyclomatic_policy)
66    .with_inline_overrides(
67        config.health.inline_threshold_overrides,
68        modules,
69        &file_paths,
70        &config.root,
71    );
72    let mut findings = Vec::new();
73
74    for module in modules {
75        let Some(path) = file_paths.get(&module.file_id) else {
76            continue;
77        };
78        let relative = path.strip_prefix(&config.root).unwrap_or(path);
79        if ignore_set.is_match(relative) {
80            continue;
81        }
82        // The rules of this file, resolved one time for all of its functions.
83        let path_rules =
84            (!config.overrides.is_empty()).then(|| config.resolve_rules_for_path(path));
85        let rules = path_rules.as_ref().unwrap_or(&config.rules);
86        for function in &module.complexity {
87            if fallow_types::extract::is_synthetic_module_unit(&function.name)
88                || crate::suppress::is_suppressed(
89                    &module.suppressions,
90                    function.line,
91                    crate::suppress::IssueKind::Complexity,
92                )
93            {
94                continue;
95            }
96            let (applied, _, _) = resolver.resolve_unit(relative, &function.name, function.line);
97            let Some((exceeds_cyclomatic, exceeds_cognitive)) =
98                super::findings::complexity_exceeded(
99                    function,
100                    resolver.cyclomatic_policy(),
101                    applied.effective,
102                )
103            else {
104                continue;
105            };
106            // A lens has no CRAP score, so only the two kinds it shows count.
107            if rules.complexity_severity(exceeds_cyclomatic, exceeds_cognitive, false)
108                == Severity::Off
109            {
110                continue;
111            }
112            findings.push(InlineComplexity {
113                path: (*path).clone(),
114                name: function.name.clone(),
115                line: function.line,
116                col: function.col,
117                cyclomatic: resolver.gate_cyclomatic(function),
118                cognitive: function.cognitive,
119                exceeds_cyclomatic,
120                exceeds_cognitive,
121            });
122        }
123    }
124
125    findings
126}