big_code_analysis_ast/getter/rust.rs
1//! `Getter` implementation for Rust.
2#![allow(clippy::wildcard_imports, clippy::enum_glob_use)]
3
4use super::*;
5
6// `for_lifetimes` (`for<'a> fn(&'a u8)`) and `use_bounds`
7// (`impl Tr + use<'a, T>`) are generic-parameter lists under other
8// names, and a qualified path's `bracketed_type` (`<T as Tr>::f`,
9// `<T>::f`) encloses a type (#1567). `LT2` is the
10// `token(prec(1, '<'))` spelling `type_arguments` and `use_bounds` open
11// with; the parser reports it as `LT`, so it is listed defensively,
12// here and in the operator arm, and its absence is pinned by
13// `rust_generic_opener_alias_never_reaches_kind_id`.
14const GENERIC_ANGLES: GenericAngleKinds = GenericAngleKinds {
15 lists: &[
16 Rust::TypeArguments as u16,
17 Rust::TypeParameters as u16,
18 Rust::ForLifetimes as u16,
19 Rust::UseBounds as u16,
20 Rust::BracketedType as u16,
21 ],
22 openers: &[Rust::LT as u16, Rust::LT2 as u16],
23 closers: &[Rust::GT as u16],
24 is_misparse: never_misparsed,
25};
26
27impl Getter for RustCode {
28 fn get_func_space_name<'a, 'tree>(
29 node: &Node<'tree>,
30 code: &'a [u8],
31 _ancestors: Ancestors<'tree, '_>,
32 ) -> Option<&'a str> {
33 // we're in a function or in a class or an impl
34 // for an impl: we've 'impl ... type {...'
35 if let Some(name) = node
36 .child_by_field_name("name")
37 .or_else(|| node.child_by_field_name("type"))
38 {
39 node_text(code, &name)
40 } else {
41 Some("<anonymous>")
42 }
43 }
44
45 // The mapping is the `opens` annotations of `roles/rust.rs`
46 // (#1696). The rows read no bytes and no chain, so the byte-less
47 // spelling forwards with none.
48 impl_byte_less_space_kind!(rust);
49
50 fn get_space_kind_with_code<'a>(
51 node: &Node<'a>,
52 code: &[u8],
53 ancestors: Ancestors<'a, '_>,
54 ) -> SpaceKind {
55 crate::roles::rust::opens_space(node, code, ancestors)
56 }
57
58 keyword_roles!(rust);
59
60 /// The `Comparison` and `ShortCircuit` rows' payers bill as
61 /// operators (#1695), except a `||` outside the owner the row
62 /// projects it from: inside a macro's `token_tree` the parser sees
63 /// no expression, and a `|| { … }` there is a closure with no
64 /// parameters, whose `||` the grammar emits as this token rather
65 /// than as `closure_parameters`. The counting consumers pay that
66 /// token — it was always a decision to them — so the row's payer is
67 /// ungated and this Halstead reading is the one place the two
68 /// policies part. `&&` has no such second spelling.
69 // role-bypass: allow(ShortCircuit) — the Halstead reading of a payer the row pays ungated: which
70 // parent makes `||` an operator rather than an empty closure's bars
71 fn get_paying_role<'a>(
72 node: &Node<'a>,
73 code: &[u8],
74 ancestors: Ancestors<'a, '_>,
75 ) -> TokenRole {
76 use crate::roles::rust::{branch, comparison, r#loop, short_circuit};
77 let kind = node.kind_id();
78 if kind == Rust::PIPEPIPE as u16
79 && !ancestors
80 .parent(node)
81 .is_some_and(|p| short_circuit::owns(&p, code, ancestors))
82 {
83 return TokenRole::Unknown;
84 }
85 // And the `Branch` / `Loop` rows' keyword payers (#1697): `if`,
86 // `for`, `while`, `loop`. A `for` in type syntax is declined by
87 // its row's gate (#1720) and falls through to the byte-less arm,
88 // which keeps `For`, so every `for` — the loop's, a macro's token
89 // tree's, the `impl` header's — bills as the operator it always did.
90 if comparison::pays_at_token_kind(kind, node, code, ancestors)
91 || short_circuit::pays_at_token_kind(kind, node, code, ancestors)
92 || branch::pays_at_token_kind(kind, node, code, ancestors)
93 || r#loop::pays_at_token_kind(kind, node, code, ancestors)
94 {
95 TokenRole::Operator
96 } else {
97 TokenRole::Unknown
98 }
99 }
100
101 fn get_op_type<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> TokenRole {
102 use Rust::*;
103
104 if GENERIC_ANGLES.is_closer(node, ancestors) {
105 return TokenRole::Unknown;
106 }
107 match node.kind_id().into() {
108 // Exclude `/` when it corresponds to the third slash in `///`
109 // (`OuterDocCommentMarker`). `||` is the `ShortCircuit` row's
110 // and `get_paying_role` decides it (#1695).
111 // role-bypass: allow(Comparison, ShortCircuit) — the `/` of `///` against a binary
112 // expression's `/`: a doc-marker test, not membership
113 SLASH => match ancestors.parent(node) {
114 Some(parent) if matches!(parent.kind_id().into(), BinaryExpression) => {
115 TokenRole::Operator
116 }
117 _ => TokenRole::Unknown,
118 },
119 // Ensure `!` is counted as an operator unless it belongs to an `InnerDocCommentMarker` `//!`
120 BANG => match ancestors.parent(node) {
121 Some(parent) if !matches!(parent.kind_id().into(), InnerDocCommentMarker) => {
122 TokenRole::Operator
123 }
124 _ => TokenRole::Unknown,
125 },
126 // COLONCOLON (`::`) is the path-segment separator. C++, Java,
127 // C#, and Kotlin all classify it as an operator; omitting it
128 // here (issue #394) silently dropped every path expression
129 // (`std::collections::HashMap`, `Vec::new`, `T::method`) into
130 // TokenRole::Unknown, deflating n1/N1 for path-heavy code.
131 //
132 // The declaration and visibility keywords and the primitive
133 // types are not here: `roles/rust.rs` declares them and
134 // `get_keyword_role` bills them (#1693; #394 added them). Nor
135 // are `==` `!=` `<=` `>=` `&&`: the `Comparison` and
136 // `ShortCircuit` rows pay them and `get_paying_role` bills
137 // them (#1695). `<` / `>` stay for the spellings the row's
138 // parent gate leaves out — a generic opener (`Vec<T>`, the
139 // `<>` pair) and a recovered token — which billed before the
140 // row existed; `LT2` is the defensive generic-opener alias.
141 // `if` / `for` / `while` / `loop` are the `Branch` / `Loop`
142 // rows' payers and `get_paying_role` bills them (#1697) — the
143 // `if` expression's keyword and a match guard's alike, so the
144 // `Guard` row's `under MatchPattern` gate no longer leaves a
145 // spelling to this arm. `for` stays: the `Loop` row's payer
146 // gate declines the type-syntax spellings (`impl T for S`,
147 // `for<'a>`) so cyclomatic does not count them (#1720), while
148 // Halstead bills every `for` as it always has — the loop's
149 // reaches `get_paying_role` first and never gets here, as
150 // Python's ternary `if` does.
151 // role-bypass: allow(Comparison, Loop) — the operator classification of the
152 // spellings the `Comparison` row's `under BinaryExpression` gate and the `Loop`
153 // row's `not_in_type_syntax` gate leave out
154 LT | LT2 | GT | LPAREN | LBRACE | LBRACK | As | EQGT | PLUS | STAR | Await | Break
155 | Continue | Else | For | In | Match | Return | EQ | COMMA | DASHGT | QMARK | AMP
156 | DOTDOT | DOTDOTEQ | DASH | PIPE | CARET | LTLT | GTGT | PERCENT | PLUSEQ | DASHEQ
157 | STAREQ | SLASHEQ | PERCENTEQ | AMPEQ | PIPEEQ | CARETEQ | LTLTEQ | GTGTEQ | DOT
158 | SEMI | COLON | COLONCOLON => TokenRole::Operator,
159 // FieldIdentifier (e.g. `p.x`) and TypeIdentifier (e.g. `Vec`,
160 // `HashMap`) are operand-class names — C++ and Go classify them
161 // the same way (see arms ~588 and ~862 below). Omitting them
162 // here silently dropped both into TokenRole::Unknown,
163 // deflating n2/N2 and the derived vocabulary/volume/effort
164 // estimates (issue #390).
165 // role-bypass: allow(StringLit) — the operand classification of the literals,
166 // a projection the `StringLit` row does not answer
167 Identifier | TypeIdentifier | FieldIdentifier | StringLiteral | RawStringLiteral
168 | IntegerLiteral | FloatLiteral | BooleanLiteral | Zelf | CharLiteral | UNDERSCORE => {
169 TokenRole::Operand
170 }
171 _ => TokenRole::Unknown,
172 }
173 }
174
175 fn get_operator_spelling<'a>(
176 node: &Node<'a>,
177 ancestors: Ancestors<'a, '_>,
178 ) -> Option<&'static str> {
179 GENERIC_ANGLES.opener_spelling(node, ancestors)
180 }
181
182 get_operator!(Rust);
183}