Skip to main content

fallow_types/
inline_threshold.rs

1//! Inline health threshold override comments.
2//!
3//! A `fallow-override-threshold-next-line` comment raises or lowers the health
4//! ceilings of the function on the next line:
5//!
6//! ```text
7//! // fallow-override-threshold-next-line maxCognitive=40 maxCrap=45 -- legacy parser
8//! ```
9//!
10//! The keys are the keys of a `health.thresholdOverrides` entry. The reason
11//! after ` -- ` is required.
12
13/// The comment word of an inline threshold override.
14pub const INLINE_THRESHOLD_MARKER: &str = "fallow-override-threshold-next-line";
15
16/// The threshold keys that an inline threshold override comment accepts.
17pub const INLINE_THRESHOLD_KEYS: [&str; 4] =
18    ["maxCyclomatic", "maxCognitive", "maxCrap", "maxUnitSize"];
19
20/// One inline threshold override comment that parsed without a problem.
21#[derive(Debug, Clone, PartialEq)]
22pub struct InlineThresholdOverride {
23    /// 1-based line that the comment applies to: the line after the comment.
24    pub line: u32,
25    /// 1-based line of the comment.
26    pub comment_line: u32,
27    /// Cyclomatic ceiling, when the comment sets one.
28    pub max_cyclomatic: Option<u16>,
29    /// Cognitive ceiling, when the comment sets one.
30    pub max_cognitive: Option<u16>,
31    /// CRAP ceiling, when the comment sets one.
32    pub max_crap: Option<f64>,
33    /// Unit-size ceiling, when the comment sets one.
34    pub max_unit_size: Option<u32>,
35    /// The reason after ` -- `.
36    pub reason: String,
37}
38
39/// What is wrong with one inline threshold override comment. A comment with a
40/// problem has no effect.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
42#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
43#[serde(rename_all = "snake_case")]
44pub enum InlineThresholdProblemKind {
45    /// The comment has no reason after ` -- `.
46    MissingReason,
47    /// The comment sets no threshold.
48    MissingThreshold,
49    /// A token is not a known key, or a key occurs two times.
50    InvalidKey,
51    /// A value is not a valid number for its key.
52    InvalidValue,
53    /// `health.inlineThresholdOverrides` is `false`, so the comment form is off.
54    Disabled,
55}
56
57impl InlineThresholdProblemKind {
58    /// Stable one-byte code for cache storage.
59    #[must_use]
60    pub const fn to_code(self) -> u8 {
61        match self {
62            Self::MissingReason => 1,
63            Self::MissingThreshold => 2,
64            Self::InvalidKey => 3,
65            Self::InvalidValue => 4,
66            Self::Disabled => 5,
67        }
68    }
69
70    /// Read a code that [`Self::to_code`] wrote.
71    #[must_use]
72    pub const fn from_code(code: u8) -> Option<Self> {
73        match code {
74            1 => Some(Self::MissingReason),
75            2 => Some(Self::MissingThreshold),
76            3 => Some(Self::InvalidKey),
77            4 => Some(Self::InvalidValue),
78            5 => Some(Self::Disabled),
79            _ => None,
80        }
81    }
82
83    /// One-sentence description for human output.
84    #[must_use]
85    pub const fn description(self) -> &'static str {
86        match self {
87            Self::MissingReason => {
88                "the comment has no reason; add ` -- <reason>` after the thresholds"
89            }
90            Self::MissingThreshold => {
91                "the comment sets no threshold; use maxCyclomatic, maxCognitive, maxCrap or maxUnitSize"
92            }
93            Self::InvalidKey => {
94                "unknown or repeated key; write each threshold as key=value (maxCyclomatic, maxCognitive, maxCrap or maxUnitSize), each one time"
95            }
96            Self::InvalidValue => {
97                "the value is not valid; use a whole number (a finite number for maxCrap), as in maxCognitive=40"
98            }
99            Self::Disabled => {
100                "health.inlineThresholdOverrides is false, so the comment has no effect"
101            }
102        }
103    }
104}
105
106/// One inline threshold override comment with a problem.
107#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
108#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
109pub struct InlineThresholdProblem {
110    /// 1-based line of the comment.
111    pub line: u32,
112    /// What is wrong with the comment.
113    #[serde(rename = "problem")]
114    pub kind: InlineThresholdProblemKind,
115    /// The token that has the problem, when one token has it.
116    #[serde(default, skip_serializing_if = "Option::is_none")]
117    pub token: Option<String>,
118}
119
120/// The inline threshold override comments of one file.
121#[derive(Debug, Clone, Default, PartialEq)]
122pub struct InlineThresholdOverrides {
123    /// The comments that parsed without a problem.
124    pub entries: Vec<InlineThresholdOverride>,
125    /// The comments with a problem. They have no effect.
126    pub problems: Vec<InlineThresholdProblem>,
127}
128
129impl InlineThresholdOverrides {
130    /// True when the file has no inline threshold override comment.
131    #[must_use]
132    pub fn is_empty(&self) -> bool {
133        self.entries.is_empty() && self.problems.is_empty()
134    }
135
136    /// Remove the comments on `comment_lines`.
137    pub fn drop_comment_lines(&mut self, comment_lines: &[u32]) {
138        self.entries
139            .retain(|entry| !comment_lines.contains(&entry.comment_line));
140        self.problems
141            .retain(|problem| !comment_lines.contains(&problem.line));
142    }
143}
144
145/// Parse the text after the marker word of one inline threshold override
146/// comment. `targets` is the text before ` -- `, and `reason` is the text
147/// after it.
148///
149/// # Errors
150///
151/// Returns the problem of the comment. A comment with a problem has no effect.
152pub fn parse_inline_threshold_override(
153    line: u32,
154    comment_line: u32,
155    targets: &str,
156    reason: Option<String>,
157) -> Result<InlineThresholdOverride, InlineThresholdProblem> {
158    let problem = |kind, token: Option<&str>| InlineThresholdProblem {
159        line: comment_line,
160        kind,
161        token: token.map(str::to_string),
162    };
163    let mut entry = InlineThresholdOverride {
164        line,
165        comment_line,
166        max_cyclomatic: None,
167        max_cognitive: None,
168        max_crap: None,
169        max_unit_size: None,
170        reason: String::new(),
171    };
172    let mut seen: Vec<&str> = Vec::new();
173    for token in targets
174        .split(|c: char| c == ',' || c.is_whitespace())
175        .filter(|token| !token.is_empty())
176    {
177        let Some((key, value)) = token.split_once('=') else {
178            return Err(problem(InlineThresholdProblemKind::InvalidKey, Some(token)));
179        };
180        if !INLINE_THRESHOLD_KEYS.contains(&key) || seen.contains(&key) {
181            return Err(problem(InlineThresholdProblemKind::InvalidKey, Some(token)));
182        }
183        seen.push(key);
184        let invalid = || problem(InlineThresholdProblemKind::InvalidValue, Some(token));
185        match key {
186            "maxCyclomatic" => entry.max_cyclomatic = Some(value.parse().map_err(|_| invalid())?),
187            "maxCognitive" => entry.max_cognitive = Some(value.parse().map_err(|_| invalid())?),
188            "maxUnitSize" => entry.max_unit_size = Some(value.parse().map_err(|_| invalid())?),
189            _ => {
190                let crap: f64 = value.parse().map_err(|_| invalid())?;
191                if !crap.is_finite() || crap < 0.0 {
192                    return Err(invalid());
193                }
194                entry.max_crap = Some(crap);
195            }
196        }
197    }
198    if seen.is_empty() {
199        return Err(problem(InlineThresholdProblemKind::MissingThreshold, None));
200    }
201    let Some(reason) = reason else {
202        return Err(problem(InlineThresholdProblemKind::MissingReason, None));
203    };
204    entry.reason = reason;
205    Ok(entry)
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211
212    fn parse(
213        targets: &str,
214        reason: Option<&str>,
215    ) -> Result<InlineThresholdOverride, InlineThresholdProblem> {
216        parse_inline_threshold_override(5, 4, targets, reason.map(str::to_string))
217    }
218
219    #[test]
220    fn parses_every_key() {
221        let entry = parse(
222            "maxCyclomatic=30 maxCognitive=40, maxCrap=45.5 maxUnitSize=120",
223            Some("legacy"),
224        )
225        .unwrap();
226        assert_eq!(entry.line, 5);
227        assert_eq!(entry.comment_line, 4);
228        assert_eq!(entry.max_cyclomatic, Some(30));
229        assert_eq!(entry.max_cognitive, Some(40));
230        assert_eq!(entry.max_crap, Some(45.5));
231        assert_eq!(entry.max_unit_size, Some(120));
232        assert_eq!(entry.reason, "legacy");
233    }
234
235    #[test]
236    fn rejects_a_comment_without_reason() {
237        let problem = parse("maxCognitive=40", None).unwrap_err();
238        assert_eq!(problem.kind, InlineThresholdProblemKind::MissingReason);
239        assert_eq!(problem.line, 4);
240    }
241
242    #[test]
243    fn rejects_a_comment_without_threshold() {
244        let problem = parse("", Some("why")).unwrap_err();
245        assert_eq!(problem.kind, InlineThresholdProblemKind::MissingThreshold);
246    }
247
248    #[test]
249    fn rejects_bad_keys_and_values() {
250        for (targets, kind, token) in [
251            (
252                "maxCognitive:40",
253                InlineThresholdProblemKind::InvalidKey,
254                "maxCognitive:40",
255            ),
256            (
257                "maxFileLines=900",
258                InlineThresholdProblemKind::InvalidKey,
259                "maxFileLines=900",
260            ),
261            (
262                "maxCognitive=40 maxCognitive=50",
263                InlineThresholdProblemKind::InvalidKey,
264                "maxCognitive=50",
265            ),
266            (
267                "maxCognitive=forty",
268                InlineThresholdProblemKind::InvalidValue,
269                "maxCognitive=forty",
270            ),
271            (
272                "maxCyclomatic=-1",
273                InlineThresholdProblemKind::InvalidValue,
274                "maxCyclomatic=-1",
275            ),
276            (
277                "maxCrap=NaN",
278                InlineThresholdProblemKind::InvalidValue,
279                "maxCrap=NaN",
280            ),
281            (
282                "maxCrap=-2",
283                InlineThresholdProblemKind::InvalidValue,
284                "maxCrap=-2",
285            ),
286        ] {
287            let problem = parse(targets, Some("why")).unwrap_err();
288            assert_eq!(problem.kind, kind, "{targets}");
289            assert_eq!(problem.token.as_deref(), Some(token), "{targets}");
290        }
291    }
292
293    #[test]
294    fn problem_codes_round_trip() {
295        for kind in [
296            InlineThresholdProblemKind::MissingReason,
297            InlineThresholdProblemKind::MissingThreshold,
298            InlineThresholdProblemKind::InvalidKey,
299            InlineThresholdProblemKind::InvalidValue,
300            InlineThresholdProblemKind::Disabled,
301        ] {
302            assert_eq!(
303                InlineThresholdProblemKind::from_code(kind.to_code()),
304                Some(kind)
305            );
306        }
307        assert_eq!(InlineThresholdProblemKind::from_code(0), None);
308    }
309}