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
//! `Cognitive` implementation for Rust.
#![allow(
clippy::enum_glob_use,
clippy::match_same_arms,
clippy::needless_pass_by_value,
clippy::wildcard_imports
)]
#![allow(
clippy::cast_precision_loss,
clippy::cast_possible_truncation,
clippy::cast_sign_loss
)]
use super::*;
impl Cognitive for RustCode {
fn compute<'a>(
node: &Node<'a>,
_code: &'a [u8],
ancestors: Ancestors<'a, '_>,
stats: &mut Stats,
nesting_map: &mut NestingMap,
) {
use Rust::*;
// Macro expansion is not tracked; macros are treated as opaque tokens.
let mut nesting = get_nesting_from_map(node, nesting_map);
match node.kind_id().into() {
IfExpression if !Self::is_else_if(node, ancestors) => {
increase_nesting(stats, &mut nesting);
}
ForExpression | WhileExpression | LoopExpression | MatchExpression => {
increase_nesting(stats, &mut nesting);
}
// `let PAT = e else { … };` is an `if let` that diverges
// instead of nesting the happy path, so it pays what its
// `if let` twin pays: a structural increment plus the current
// nesting, and a level for everything under it — the `else`
// block included, as the twin's body is (#1548). Keyed on the
// `alternative` field, as cyclomatic does (#1542).
LetDeclaration if node.child_by_field_name("alternative").is_some() => {
increase_nesting(stats, &mut nesting);
}
// `Else` here is the `else` keyword token, which the grammar
// also emits for the `else` of an `else if` — so this arm
// covers both. A `let`-`else`'s token is a direct child of the
// `let_declaration`, which the arm above already charged.
Else if !ancestors.parent_has_kind(node, LetDeclaration as u16) => {
increment_by_one(stats);
}
BreakExpression | ContinueExpression => {
if let Some(label_child) = node.child(1)
&& let Label = label_child.kind_id().into()
{
increment_by_one(stats);
}
}
// `LetChain` (the visible alias) and `LetChain2` (the hidden
// `_let_chain` supertype) are Rust 2024 let-chains:
// `if let Some(x) = a && let Some(y) = b && cond`. Their `&&`
// tokens are direct children of the chain node — not wrapped
// in `BinaryExpression` — so without dispatching them through
// `compute_booleans` here, let-chain `&&` is invisible to the
// boolean-sequence counter (issue #396). Cyclomatic already
// counts the same tokens via the AMPAMP keyword arm.
BinaryExpression | LetChain | LetChain2 => {
compute_booleans(node, stats, AMPAMP, PIPEPIPE);
}
FunctionItem => {
enter_function_boundary(&mut nesting, node, ancestors, &[FunctionItem]);
}
ClosureExpression => {
nesting.lambda += 1;
}
_ => {}
}
nesting_map.insert(node.id(), nesting);
}
}