big_code_analysis_ast/getter/cpp.rs
1//! `Getter` implementation for C++.
2#![allow(clippy::wildcard_imports, clippy::enum_glob_use)]
3
4use super::*;
5use crate::c_declarator::declarator_name;
6
7// `GT2` is the template closer's own symbol, which the parser folds
8// onto `GT` (`cpp_template_closer_alias_never_reaches_kind_id`); it is
9// listed defensively.
10const GENERIC_ANGLES: GenericAngleKinds = GenericAngleKinds {
11 lists: &[
12 Cpp::TemplateArgumentList as u16,
13 Cpp::TemplateParameterList as u16,
14 ],
15 openers: &[Cpp::LT as u16],
16 closers: &[Cpp::GT as u16, Cpp::GT2 as u16],
17 is_misparse: never_misparsed,
18};
19
20impl Getter for CppCode {
21 fn get_func_space_name<'a, 'tree>(
22 node: &Node<'tree>,
23 code: &'a [u8],
24 _ancestors: Ancestors<'tree, '_>,
25 ) -> Option<&'a str> {
26 // Every `function_definition` alias the `FuncOpener` row names is
27 // listed here too (#285): a dropped one would fall through to
28 // the `_ => name-field` arm and yield the wrong name (or `None`).
29 // role-bypass: allow(FuncOpener) — a naming rule, not whether the
30 // definition opens a space
31 match node.kind_id().into() {
32 Cpp::FunctionDefinition
33 | Cpp::FunctionDefinition2
34 | Cpp::FunctionDefinition3
35 | Cpp::FunctionDefinition4 => {
36 if let Some(op_cast) = node.first_child(|id| Cpp::OperatorCast == id) {
37 return node_text(code, &op_cast);
38 }
39 // The name is not a child of the function node — see
40 // `crate::c_declarator` (#1208).
41 if let Some(name) = declarator_name::<Self>(node)
42 && matches!(
43 name.kind_id().into(),
44 Cpp::TypeIdentifier
45 | Cpp::Identifier
46 | Cpp::FieldIdentifier
47 | Cpp::DestructorName
48 | Cpp::OperatorName
49 | Cpp::QualifiedIdentifier
50 | Cpp::QualifiedIdentifier2
51 | Cpp::QualifiedIdentifier3
52 | Cpp::QualifiedIdentifier4
53 | Cpp::TemplateFunction
54 | Cpp::TemplateMethod
55 )
56 {
57 return node_text(code, &name);
58 }
59 }
60 _ => {
61 if let Some(name) = node.child_by_field_name("name") {
62 return node_text(code, &name);
63 }
64 }
65 }
66 None
67 }
68
69 // The mapping is the `opens` annotations of `roles/cpp.rs`
70 // (#1696). The rows read no bytes and no chain, so the byte-less
71 // spelling forwards with none.
72 impl_byte_less_space_kind!(cpp);
73
74 fn get_space_kind_with_code<'a>(
75 node: &Node<'a>,
76 code: &[u8],
77 ancestors: Ancestors<'a, '_>,
78 ) -> SpaceKind {
79 crate::roles::cpp::opens_space(node, code, ancestors)
80 }
81
82 keyword_roles!(cpp);
83
84 paying_roles!(cpp, control_flow);
85
86 fn get_op_type<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> TokenRole {
87 use Cpp::*;
88
89 if GENERIC_ANGLES.is_closer(node, ancestors) {
90 return TokenRole::Unknown;
91 }
92
93 // `LPAREN2` here (and the `LBRACK2`/`LBRACK3` aliases in the
94 // Elixir/Ruby impls) is a defensive arm, not an active one: every
95 // grammar's `public_symbol_map` collapses the second-alias opener
96 // to its base before `Node::kind_id()` (`ts_node_symbol`) returns,
97 // so `kind_id()` never yields the alias id and the arm cannot fire
98 // for real source. It guards against a future grammar bump that
99 // drops that collapse — at which point the alias would also need
100 // folding to its pair glyph in `get_operator_id_as_str`. The
101 // invariant is pinned by `second_alias_opener_collapses_to_base_kind_id`
102 // in `metrics/halstead.rs` (issue #768).
103 // The modifiers, the declaration keywords and the primitive
104 // types are not here: `roles/cpp.rs` declares them and
105 // `get_keyword_role` bills them (#1693). The comparison and
106 // short-circuit tokens are read from the `Comparison` and
107 // `ShortCircuit` rows by `get_paying_role` where they apply
108 // their operator; the arm below keeps the spellings the rows'
109 // `applied` gate leaves out (#1694).
110 match node.kind_id().into() {
111 // Raw-string delimiter punctuation. A `raw_string_literal`
112 // carries its `R"(` opener as a bare `LPAREN` child — the
113 // kind id a call or a grouping uses — so `R"(raw)"`
114 // reported a `()` operator with no call in the source
115 // (#1314, the C++ sibling of Elixir #1256 and Ruby/Perl
116 // #1312). The literal is already an operand (below), so the
117 // delimiter is suppressed exactly when its parent is that
118 // node — the compound-leaf guard of grammar-dispatch
119 // section 5. Verified across `R"(x)"`, the custom-delimiter
120 // `R"tag(x)tag"` (which adds a `raw_string_delimiter` but
121 // keeps the same `(`), and the `LR` / `u8R` prefixed forms;
122 // the closing `)` needs no arm because #695 dropped every
123 // closer from the operator set.
124 //
125 // Parent, not ancestor. That distinction is unobservable
126 // here — `raw_string_content` is a leaf, so no `LPAREN` is
127 // ever a deeper descendant of a raw string — but parent
128 // scoping is correct by construction and keeps this arm the
129 // same shape as its siblings. `mozcpp` carries the twin.
130 LPAREN
131 if ancestors.parent_has_kind(node, RawStringLiteral as u16) =>
132 {
133 TokenRole::Unknown
134 }
135 // The comparison and short-circuit tokens (`<` … `<=>`,
136 // `not_eq`, `&&`, `||`, `and`, `or`) sit in this arm for the
137 // spellings that apply no operator — an overload name
138 // (`operator<`, `operator and`), a reference declarator or
139 // ref-qualifier (`int&& x`, `void f() &&`), a requires-
140 // clause's constraint conjunction (`requires A<T> && B<T>`),
141 // a template delimiter's `<` (the `<>` pair; its closer
142 // returned `Unknown` above) and a token error recovery
143 // reparents — which bill as the operators they spell, as
144 // they did before the rows existed. The rows pay the applied
145 // spellings and this arm the rest; for these kinds the
146 // Halstead vocabulary is the union, so dropping one from a
147 // row moves nothing here. The ternary `?` and the `case` label
148 // are not here: the `Ternary` and `CaseArm` rows pay them
149 // ungated.
150 // The `if` / `for` / `while` / `catch` keywords are the `Branch` /
151 // `Loop` / `Catch` rows' payers and `get_paying_role` bills them
152 // (#1697).
153 // role-bypass: allow(Comparison, ShortCircuit) — the operator classification of the
154 // spellings the rows' `applied` gate leaves out
155 LT | LTEQ | EQEQ | BANGEQ | GTEQ | GT | GT2 | LTEQGT | NotEq | AMPAMP | PIPEPIPE
156 | And | Or
157 | DOT | DOTSTAR | LPAREN | LPAREN2 | COMMA | STAR | GTGT | COLON | SEMI | Return
158 | Break | Continue | Else | Switch | Default | Goto | Do
159 | Delete | New | Try | Try2 | Throw | EQ | DASH
160 | DASHDASH | DASHGT | DASHGTSTAR | PLUS | PLUSPLUS | SLASH | PERCENT | PIPE | AMP
161 | LTLT | TILDE | PLUSEQ
162 | DASHEQ | BANG | STAREQ | SLASHEQ | PERCENTEQ | GTGTEQ | LTLTEQ | AMPEQ | CARET
163 | CARETEQ | PIPEEQ | LBRACK | LBRACE | COLONCOLON | Sizeof
164 // The ISO alternative tokens ([lex.digraph]): `not`, `compl`,
165 // `and`, `or`, `bitand`, `bitor`, `xor`, `not_eq`, `and_eq`,
166 // `or_eq`, `xor_eq` spell `!`, `~`, `&&`, `||`, `&`, `|`, `^`,
167 // `!=`, `&=`, `|=`, `^=`. The grammar gives each a kind of its
168 // own, so without these they fell into `Unknown` and `b and c`
169 // billed no operator at all (#1522). Each kind occurs only in
170 // productions its symbol also occurs in, so it needs no gate
171 // the symbol lacks. Keyed by `kind_id` like every operator, so
172 // `and` and `&&` are two distinct operators in n1: the `ops`
173 // vocabulary names operators by kind, and folding the two in
174 // the metric alone would make the two stores disagree. `and`,
175 // `or` and `not_eq` sit in the arm above with their symbols.
176 | Not | Compl | Bitand | Bitor | Xor | AndEq | OrEq | XorEq
177 // An overloaded operator's name (#1296). `operator +` already
178 // billed its `+` through the punctuation kind, but the grammar
179 // spells four overloadable names as whole tokens of their own
180 // — `[]`, `()`, the `""` of a user-defined literal and
181 // `co_await` — and none was in either arm, so
182 // `operator[]` and `operator()` billed nothing for the name
183 // that tells them apart. `Operator` is the `operator` keyword
184 // itself, which C# bills the same way. `CoAwait` is also the
185 // keyword of `co_await expr`, an operator there too. Each
186 // token occurs only under `operator_name`, `operator_cast` or
187 // `co_await_expression`, none of which is classified, so
188 // nothing bills one twice (grammar-dispatch section 5).
189 //
190 // `LPARENRPAREN` / `LBRACKRBRACK` are kinds of their own, not
191 // the `LPAREN` / `LBRACK` of a call or subscript, so declaring
192 // `operator[]` and applying `s[1]` are two `n1` entries, which
193 // `bca ops` renders `operator[]` and `[]` (see
194 // `get_operator_id_as_str`).
195 | LPARENRPAREN | LBRACKRBRACK | DQUOTEDQUOTE | CoAwait | Operator
196 // `co_return` and `co_yield` are the coroutine spellings of
197 // `return` and of handing a value back, so they bill as
198 // `return` does (#1547). Each is the keyword leaf of a
199 // `co_return_statement` / `co_yield_statement`, which no arm
200 // classifies, so nothing bills one twice.
201 | CoReturn | CoYield
202 => TokenRole::Operator,
203 // `CharLiteral` — the full derivation lives on the same arm
204 // in `src/getter/c.rs` (#1316): the wrapper is the only
205 // classified node in a character literal, so it bills one
206 // operand per literal, keyed by text, and `Checker::is_string`
207 // deliberately stays without a `CharLiteral` arm.
208 //
209 // `This` was in *neither* arm until #1361, so a C++ `this`
210 // contributed nothing at all: not an operator and not an
211 // operand. Same shape as #1316, opposite of the #1351-#1355
212 // wrapper/leaf over-counts — the fix adds an arm rather than
213 // deleting one.
214 //
215 // Operand, not operator, on three grounds. **Structure**:
216 // `field_expression` is `<receiver> -> <field>`, and `p->x`
217 // already bills operands `p` / `x` around the `->` operator.
218 // Calling `this` an operator would make `this->x` a binary
219 // operator with one operand, and would score the identical
220 // AST differently for `this->x` than for `p->x`.
221 // **Role**: `this` is a pointer *rvalue* and stands exactly
222 // where a variable stands — `return this;`, `*this`,
223 // `f(this)`, which would otherwise pass an operator as a
224 // call argument — while `->` / `.` / `*` are the operators
225 // already counted acting on it. **Precedent**: eleven of the
226 // fourteen languages here bill their self-reference as an
227 // operand (Rust `Zelf`, Ruby `Zelf`, PHP's `$this`
228 // `variable_name`, the four JS-family `This` arms, and
229 // Python / ObjC / Groovy / Lua, whose grammars spell it a
230 // plain `identifier`), and the JS-family arm in
231 // `src/getter.rs` is the only *reasoned* one among them —
232 // its `MetaProperty` note calls `this` "one atomic
233 // operand". Java / C# / Kotlin disagree, but each
234 // swept `This` in as one entry in a run of keywords — under
235 // `// Operator: keywords`, `// Operator: other keywords` and
236 // `// Expression-keyword operators` respectively — grouping
237 // it by lexical class rather than by Halstead role; that
238 // three-way split is #1380, deliberately not settled here.
239 // Keeping C++ an operand also keeps it agreeing with ObjC,
240 // whose `self` is an operand and whose `.mm` files route to
241 // this very impl.
242 //
243 // Safe against a grammar-dispatch section 5 double count:
244 // `this` is a childless leaf in every position the grammar
245 // admits it — `this->x`, `(*this)`, `return this`, `f(this)`,
246 // the `[this]` and `[=, this]` lambda captures, a
247 // `decltype(this->x)` trailing return type, and a
248 // constructor body after a member-initialiser list — and no
249 // node that *contains* it (`field_expression`,
250 // `pointer_expression`, `lambda_capture_specifier`,
251 // `argument_list`) is classified, so it can double-count in
252 // neither direction. Neither generated enum aliases the rule
253 // (`This = 215` is the sole variant spelling `"this"` in
254 // `language_cpp.rs` and `language_mozcpp.rs`), so there is no
255 // `This2` for a single-variant arm to miss;
256 // `cpp_this_is_a_childless_unaliased_leaf` pins both facts.
257 //
258 // C++23's explicit object parameter (`int g(this S&& self)`)
259 // does *not* reach this arm: the pinned grammar cannot parse
260 // it and emits `type_identifier "this"` plus an `ERROR`. That
261 // spelling is already an operand via `TypeIdentifier`, so the
262 // construct is unaffected either way.
263 // role-bypass: allow(StringLit) — the operand classification of the literals,
264 // a projection the `StringLit` row does not answer
265 Identifier | TypeIdentifier | FieldIdentifier | RawStringLiteral | StringLiteral
266 | CharLiteral | NumberLiteral | True | False | Null | This | DOTDOTDOT => {
267 TokenRole::Operand
268 }
269 // A namespace identifier is an operand only where it
270 // *names* a namespace; the same kind also spells the
271 // qualifier in `ns::thing`, which the final arm leaves
272 // `Unknown` (#1096).
273 NamespaceIdentifier if ancestors.parent_has_kind(node, NamespaceDefinition as u16) => {
274 TokenRole::Operand
275 }
276 _ => TokenRole::Unknown,
277 }
278 }
279
280 fn get_operator_spelling<'a>(
281 node: &Node<'a>,
282 ancestors: Ancestors<'a, '_>,
283 ) -> Option<&'static str> {
284 GENERIC_ANGLES.opener_spelling(node, ancestors)
285 }
286
287 // `get_operator!`'s three bracket arms, plus the two overloaded
288 // operator names (#1296). The grammar names `LPARENRPAREN` /
289 // `LBRACKRBRACK` `()` / `[]`, the same text a call's and a
290 // subscript's opener render as, so `bca ops` would list one spelling
291 // for two `n1` entries. Rendering each as the operator it names keeps
292 // every listed operator distinct (lesson 4).
293 fn get_operator_id_as_str(id: u16) -> &'static str {
294 let typ = id.into();
295 match typ {
296 Cpp::LPAREN => "()",
297 Cpp::LBRACK => "[]",
298 Cpp::LBRACE => "{}",
299 Cpp::LPARENRPAREN => "operator()",
300 Cpp::LBRACKRBRACK => "operator[]",
301 _ => typ.into(),
302 }
303 }
304}