Skip to main content

big_code_analysis_ast/getter/
php.rs

1//! `Getter` implementation for PHP.
2#![allow(clippy::wildcard_imports, clippy::enum_glob_use)]
3
4use super::*;
5
6impl Getter for PhpCode {
7    // The mapping is the `opens` annotations of `roles/php.rs`
8    // (#1696). The rows read no bytes and no chain, so the byte-less
9    // spelling forwards with none.
10    impl_byte_less_space_kind!(php);
11
12    fn get_space_kind_with_code<'a>(
13        node: &Node<'a>,
14        code: &[u8],
15        ancestors: Ancestors<'a, '_>,
16    ) -> SpaceKind {
17        crate::roles::php::opens_space(node, code, ancestors)
18    }
19
20    // PHP bills a primitive type as an operand (#1293): the row says
21    // which nodes name a type, and this says what Halstead makes of
22    // one here, where the C family, Java and TypeScript say operator.
23    keyword_roles!(php, primitive: Operand);
24
25    paying_roles!(php);
26
27    fn get_op_type<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> TokenRole {
28        use Php::*;
29        match node.kind_id().into() {
30            // String-interpolation opener. `LBRACE` is *both* the
31            // compound-statement brace and the complex-interpolation
32            // opener, so `"dq {$y} end"` reported a `{}` operator —
33            // and reported it against the same vocabulary entry a real
34            // block uses, which no other language does (#1314).
35            //
36            // An interpolation opener is spelling, not an operation:
37            // the interpolated expression's own operators are already
38            // counted, and no reader performs a `{`. Measured across
39            // the six interpolating languages here, `[n1, N1]` on one
40            // fixture with and without an interpolation: kotlin
41            // [5,7]->[5,7], csharp [8,11]->[8,11], groovy's `${` (142)
42            // absent from its operator arm, ruby [1,2]->[2,3], php
43            // [2,4]->[3,5], and elixir counting it through the same
44            // `HASHLBRACE` token as Ruby. Three of six already
45            // declined to count it; this arm plus the Ruby and Elixir
46            // `#{` drops on this branch make it six of six.
47            //
48            // Four parents, not one. The opener is a direct child of
49            // `encapsed_string` (`"{$y}"`), of `heredoc_body` — the
50            // body, not `heredoc` — of `shell_command_expression`
51            // (`` `ls {$y}` ``), and of `dynamic_variable_name`, which
52            // covers both the in-string `"${y}"` form and a bare
53            // `${$y}` variable-variable. `"${y}"` is deprecated as of
54            // PHP 8.2 and removed in 9.0, but the grammar still parses
55            // it and it is still in the wild.
56            //
57            // Parent, not ancestor, and PHP is one of only two
58            // languages in #1314 where that is observable: a closure
59            // inside an interpolation (`"{$o->m(function() { … })}"`)
60            // puts a compound-statement brace under an
61            // `encapsed_string` ancestor. Pinned by
62            // `php_interpolation_guard_is_parent_scoped_not_ancestor_scoped`.
63            //
64            // A literal brace in string text (`"lit { brace"`) never
65            // reaches here — the grammar folds it into `string_content`
66            // — so nothing is over-suppressed.
67            // role-bypass: allow(StringLit) — the `{` and the literal kinds the row
68            // `wraps` / owns, read for which brace is an interpolation opener;
69            // not whether the node is a string
70            LBRACE
71                if matches!(
72                    ancestors.parent(node).map(|p| p.kind_id().into()),
73                    Some(
74                        EncapsedString
75                            | HeredocBody
76                            | ShellCommandExpression
77                            | DynamicVariableName
78                    )
79                ) =>
80            {
81                TokenRole::Unknown
82            }
83            // Operator: control-flow keywords. `?` stays in this arm for
84            // the spelling the `Ternary` row's gate leaves out — an
85            // optional type's `?int` — which billed before the row
86            // existed.
87            // role-bypass: allow(Ternary, StringLit) — the operator classification of the
88            // spelling the row's `under ConditionalExpression` gate leaves out (an optional
89            // type), and of the `{` the `StringLit` row `wraps` as an interpolation opener
90            If | Else | Elseif | Endif
91            | Switch | Case | Default | Endswitch
92            | For | Endfor | Foreach | Endforeach
93            | While | Endwhile | Do
94            | Break | Continue
95            | Return | Throw | Try | Catch | Finally
96            | Match | Yield | Yieldfrom | Goto
97            | Echo | Exit | Print
98            | Include | IncludeOnce | Require | RequireOnce
99
100            // Operator: expression keywords. The modifiers and the
101            // declaration keywords are not here: `roles/php.rs`
102            // declares them and `get_keyword_role` bills them (#1693).
103            | New | Clone | As | Insteadof | Extends | Implements
104            | Enddeclare | Unset | List
105            | Zelf | Parent
106
107            // Operator: structural punctuation. Only the *opening*
108            // delimiter is an operator (the pair folds to one glyph in
109            // `get_operator_id_as_str`); the former closing arms
110            // (`RBRACE`/`RPAREN`/`RPAREN2`/`RBRACK`) double-counted every
111            // balanced pair, inflating n1/N1 (#695). `LPAREN2` is defensive —
112            // the runtime collapses it to `LPAREN` before `kind_id()`, so it
113            // never fires (#768; see the Cpp note).
114            | LBRACE | LPAREN | LPAREN2
115            | LBRACK
116            | COMMA | SEMI | COLON | COLONCOLON
117            | DASHGT | EQGT | BSLASH | DOTDOTDOT | QMARK | AT
118            | HASHLBRACK
119
120            // Operator: arithmetic
121            | PLUS | DASH | STAR | SLASH | PERCENT | STARSTAR
122            | PLUSPLUS | DASHDASH
123
124            // The comparison tokens, `instanceof`, `&&`, `||`, `and` and
125            // `or` are the `Comparison` and `ShortCircuit` rows' and
126            // `get_paying_role` bills them (#1695).
127
128            // Operator: logical; `xor` is the `EagerLogical` row's and
129            // `??` and `?->` the `NullSafe` row's, which `get_paying_role`
130            // bills (#1695); `??=` is excluded there and bills below as
131            // the assignment it is
132            | BANG
133
134            // Operator: bitwise
135            | AMP | PIPE | CARET | TILDE | LTLT | GTGT
136
137            // Operator: assignment
138            | EQ
139            | PLUSEQ | DASHEQ | STAREQ | SLASHEQ | PERCENTEQ | STARSTAREQ
140            | DOTEQ | QMARKQMARKEQ
141            | AMPEQ | PIPEEQ | CARETEQ | LTLTEQ | GTGTEQ
142
143            // Operator: string concat
144            | DOT
145                => TokenRole::Operator,
146
147            // `name` is a genuine operand almost everywhere — function,
148            // class, const, member (`->prop`) and namespace-component
149            // identifiers are all this kind. But it is ALSO the identifier
150            // leaf of every variable reference: `$x` parses as a
151            // `variable_name` wrapping `name`, and `"${x}"` as a
152            // `dynamic_variable_name` wrapping it directly. Both wrappers
153            // are operands in their own right below (keyed with the `$`
154            // sigil, the way Bash and iRules key theirs), so counting the
155            // leaf too double-counts every variable reference — inflating
156            // N2 and adding a spurious sigil-less twin to n2 (#1259).
157            // Exclude it exactly in those two positions, the same
158            // parent-scoped guard Bash applies to `variable_name` under
159            // `simple_expansion` and iRules to `Id` under
160            // `variable_substitution`. `Name2` is the hidden `_name`
161            // supertype the parser never emits — pinned by
162            // `php_name2_hidden_rule_drift_marker` in `src/metrics/abc.rs`.
163            // It rides along defensively so a grammar bump that promotes
164            // it inherits the guard rather than the bug.
165            // role-bypass: allow(StringLit) — a name under the variable kinds the row
166            // `wraps`, read for whether it is billed once; not whether it interpolates
167            Name | Name2 => match ancestors.parent(node).map(|p| p.kind_id().into()) {
168                Some(VariableName | DynamicVariableName) => TokenRole::Unknown,
169                _ => TokenRole::Operand,
170            },
171
172            // Variable-variable syntax nests these wrappers: `$$x` is a
173            // `dynamic_variable_name` around a `variable_name`, `${$x}`
174            // the same, and `$$$x` a `dynamic_variable_name` around
175            // another `dynamic_variable_name`. Each level's text span
176            // contains the one below it, so only the outermost may count;
177            // suppressing both kinds under a `dynamic_variable_name`
178            // parent handles arbitrary depth (#1259). An inner reference
179            // reached through a real expression (`${$x . 'y'}`, whose
180            // `$x` hangs off a `binary_expression`) is unaffected.
181            // role-bypass: allow(StringLit) — the operand classification of the variable
182            // kinds the row `wraps`, a projection the row does not answer
183            VariableName | DynamicVariableName => {
184                match ancestors.parent(node).map(|p| p.kind_id().into()) {
185                    Some(DynamicVariableName) => TokenRole::Unknown,
186                    _ => TokenRole::Operand,
187                }
188            }
189
190            // `named_type`, `optional_type`, `union_type`,
191            // `intersection_type`, `disjunctive_normal_form_type`,
192            // `qualified_name`, `relative_name` and `namespace_name`
193            // are deliberately absent from the operand arm below and
194            // fall through to the `_ => Unknown` catch-all (#1293).
195            // They cannot be spelled as an explicit `Unknown` arm —
196            // `clippy::match_same_arms` rejects one that duplicates the
197            // catch-all — so the rationale lives here.
198            //
199            // Each of them spans exactly the text of the node(s) it
200            // contains plus separator glyphs that `get_op_type` already
201            // counts as *operators* — `?` (`QMARK`), `|` (`PIPE`), `&`
202            // (`AMP`), the DNF parens, and `\` (`BSLASH`). Counting the
203            // wrapper as well billed the same bytes two to five times:
204            // `?A\B` nests `optional_type` → `named_type` →
205            // `qualified_name` → `namespace_name` → `name` and scored 6
206            // operands for two identifiers.
207            //
208            // Both design calls this needed, recorded so the next
209            // reader does not have to re-derive them:
210            //
211            // * A type's operand is the innermost concrete type, not
212            //   the decorated form: `?int` is the operand `int`, not
213            //   `?int`. The `?` is already an operator, so folding it
214            //   into the operand text bills nullability across both
215            //   Halstead halves and splits `int` and `?int` into two
216            //   vocabulary entries for one type.
217            // * A qualified name's operands are its components, not
218            //   the whole path: `Foo\Bar\Baz` is `Foo`, `Bar`, `Baz`
219            //   with two `\` operators. That is exactly how PHP's own
220            //   sibling separators already read here — `Foo::bar`
221            //   yields operands `Foo` / `bar` around a `::` operator,
222            //   `$o->prop` yields `$o` / `prop` around `->` — and how
223            //   Rust's `foo::bar::baz` reads. The whole-path reading
224            //   would instead plant a distinct vocabulary entry per
225            //   prefix (`Foo`, `Foo\Bar`, `Foo\Bar\Baz`).
226            //
227            // Dropping these kinds rather than gating a leaf is safe
228            // here, unlike `primitive_type` below: every one of them is
229            // grammatically required to contain the node that now
230            // carries the operand (a `named_type` always wraps a `name`
231            // or `qualified_name`, a `namespace_name` always holds at
232            // least one `name`), so no spelling regresses to zero the
233            // way grammar-dispatch §6 warns about.
234
235            // The primitive-type keyword tokens, suppressed under a
236            // `primitive_type` wrapper (#1293). Here the wrapper is the
237            // node that carries the operand and the leaf is the
238            // duplicate — the opposite of the qualified-name arm above,
239            // and deliberately so: `primitive_type` is *childless* for
240            // `callable`, `iterable`, `mixed`, `void`, `false` and
241            // `true` (verified with `bca dump`; the grammar emits no
242            // token node for those spellings), so dropping the wrapper
243            // would score those six types zero — grammar-dispatch §6
244            // exactly. The wrapper's text equals the keyword's, so
245            // `n2` is unchanged and only the duplicate `N2` occurrence
246            // goes away.
247            //
248            // Parent-scoped, not a blanket exclusion: `array` is also
249            // the head token of `array(1, 2)` and must keep counting
250            // there, and a `(string)` cast is a childless `cast_type`
251            // that never reaches this arm.
252            //
253            // Cross-walk (grammar-dispatch §7): `Checker::is_string`
254            // agrees — #1474 withdrew `String2` from it on the strength
255            // of this arm, so a `: string` return type is neither a
256            // Halstead operand here nor a literal to `find string`.
257            // The *span* keeps its operand either way: the enclosing
258            // `primitive_type` carries it, and only the node it is
259            // attributed to moved.
260            // role-bypass: allow(Primitive) — the operand classification of a leaf under the
261            // row's wrapper, which carries the operand; not whether the leaf is a primitive
262            Int | Bool | Array | Object | String2 | Float2 | Null2 => {
263                match ancestors.parent(node).map(|p| p.kind_id().into()) {
264                    Some(PrimitiveType) => TokenRole::Unknown,
265                    _ => TokenRole::Operand,
266                }
267            }
268
269            // Operands: literals. `String` (368) is the single-quoted
270            // string literal and `String3` the hidden `_string`
271            // supertype — the `string` *type* keyword is `String2`
272            // (25), handled above. Neither `String` nor `Nowdoc` ever
273            // interpolates, so both are always one operand. The type
274            // nodes that carry the operand themselves (`primitive_type`,
275            // `bottom_type`, `cast_type`) are the `Primitive` row's,
276            // billed as operands by `get_keyword_role`.
277            // role-bypass: allow(StringLit) — the operand classification of the literals,
278            // a projection the `StringLit` row does not answer
279            Integer | Float
280            | String | String3
281            | Nowdoc
282            | Boolean | Null
283                => TokenRole::Operand,
284
285            // `EncapsedString` (double-quoted), `Heredoc`, and
286            // `ShellCommandExpression` (backticks) count as one
287            // operand when inert. When they carry a `$var`,
288            // `${name}`, or `{$expr}` interpolation child, those
289            // inner expressions are already walked and classified as
290            // operands in their own right; counting the wrapping
291            // literal too would double-count their contribution to
292            // `N2` (issue #184, same pattern as #180 for Elixir/Bash
293            // and #183 for C#). `ShellCommandExpression` was previously
294            // omitted entirely (issue #288), so backtick literals
295            // contributed no Halstead operand at all even when inert.
296            // role-bypass: allow(StringLit) — the operand classification of the literals
297            // under the row's `wraps` list, a projection the row does not answer
298            EncapsedString | Heredoc | ShellCommandExpression => {
299                // PHP's interpolation children appear directly on the
300                // wrapping literal, except `Heredoc`, which holds them
301                // one level down under a single `heredoc_body` child —
302                // so the descend below mirrors the original
303                // `php_string_has_interpolation` two-level walk.
304                // The interpolation kinds are the `StringLit` row's `wraps`
305                // list (`roles/php.rs`), which records each spelling.
306                const PHP_INTERP_KINDS: &[u16] = crate::roles::php::string_lit::WRAPS;
307                // Single pass over the direct children: an interpolation
308                // child on the literal itself (EncapsedString /
309                // ShellCommandExpression) OR, for Heredoc, one nested under
310                // its `heredoc_body` child. Folding both checks into one walk
311                // avoids re-scanning the children a second time through
312                // `string_operand_type` for an inert heredoc.
313                let has_interp = node.children().any(|c| {
314                    let kind = c.kind_id();
315                    PHP_INTERP_KINDS.contains(&kind)
316                        || (kind == HeredocBody as u16 && c.wraps_any(PHP_INTERP_KINDS))
317                });
318                if has_interp {
319                    TokenRole::Unknown
320                } else {
321                    TokenRole::Operand
322                }
323            }
324
325            _ => TokenRole::Unknown,
326        }
327    }
328
329    get_operator!(Php);
330}