big_code_analysis_ast/getter/bash.rs
1//! `Getter` implementation for Bash.
2#![allow(clippy::wildcard_imports, clippy::enum_glob_use)]
3
4use super::*;
5
6impl Getter for BashCode {
7 // The mapping is the `opens` annotations of `roles/bash.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!(bash);
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::bash::opens_space(node, code, ancestors)
18 }
19
20 keyword_roles!(bash);
21
22 /// The `Comparison` and `ShortCircuit` rows' payers bill as
23 /// operators (#1695), except a `test_operator`: the grammar gives
24 /// `-z`, `-eq`, `-lt`, `-a`, `-o`, … one kind that this getter has
25 /// never billed — a test operator names a predicate as a `test`
26 /// builtin's flag does — and the rows' text gates split it for the
27 /// counting consumers only. That reading stays here, where the
28 /// macro cannot express it.
29 // role-bypass: allow(Comparison, ShortCircuit) — the Halstead reading of a payer the rows
30 // text-gate: a test operator bills nothing, as before the rows
31 fn get_paying_role<'a>(
32 node: &Node<'a>,
33 code: &[u8],
34 ancestors: Ancestors<'a, '_>,
35 ) -> TokenRole {
36 use crate::roles::bash::{comparison, short_circuit, ternary};
37 let kind = node.kind_id();
38 if kind == Bash::TestOperator as u16 {
39 return TokenRole::Unknown;
40 }
41 if comparison::pays_at_token_kind(kind, node, code, ancestors)
42 || short_circuit::pays_at_token_kind(kind, node, code, ancestors)
43 || ternary::pays_at_token_kind(kind, node, code, ancestors)
44 {
45 TokenRole::Operator
46 } else {
47 TokenRole::Unknown
48 }
49 }
50
51 fn get_op_type<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> TokenRole {
52 match node.kind_id().into() {
53 // Control flow keywords and the undeclaring builtins. The
54 // declaration keywords are not here: `roles/bash.rs`
55 // declares them and `get_keyword_role` bills them (#1693).
56 Bash::If | Bash::Then | Bash::Fi | Bash::Elif | Bash::Else
57 | Bash::For | Bash::In | Bash::While | Bash::Until | Bash::Do | Bash::Done
58 | Bash::Case | Bash::Esac
59 | Bash::Unset | Bash::Unsetenv
60 // Punctuation acting as operators. Only the *opening*
61 // delimiter counts — `get_operator_id_as_str` folds
62 // `LPAREN`/`LBRACK`/`LBRACE` to the pair glyph, so a balanced
63 // pair is one operator. Counting the matching closer too
64 // (former `RPAREN`/`RBRACE`/`RBRACK`/`RBRACKRBRACK` arms)
65 // double-counted every pair, inflating n1/N1 (#695). `[[`
66 // (`LBRACKLBRACK`) is the test-command opener; its `]]` closer
67 // is dropped for the same reason.
68 | Bash::LPAREN | Bash::LBRACE
69 | Bash::LBRACK | Bash::LBRACKLBRACK
70 | Bash::SEMI | Bash::SEMISEMI | Bash::SEMIAMP | Bash::SEMISEMIAMP
71 | Bash::COMMA | Bash::COLON
72 // Assignment, arithmetic, and comparison operators
73 | Bash::EQ | Bash::PLUSEQ | Bash::DASHEQ | Bash::STAREQ | Bash::SLASHEQ
74 | Bash::PERCENTEQ | Bash::STARSTAREQ | Bash::LTLTEQ | Bash::GTGTEQ
75 | Bash::AMPEQ | Bash::CARETEQ | Bash::PIPEEQ
76 | Bash::PLUS | Bash::DASH | Bash::STAR | Bash::SLASH | Bash::PERCENT | Bash::STARSTAR
77 | Bash::PLUSPLUS | Bash::DASHDASH
78 // `<` / `>` for the spelling the `Comparison` row's parent
79 // gate leaves out — a redirection (`cmd > out`) — which billed
80 // before the row existed; the other comparison tokens and
81 // `&&` / `||` are the rows' and `get_paying_role` bills them
82 // (#1695). `?` likewise stays, below, for the `Ternary` row's
83 // gated-out expansion spelling.
84 // role-bypass: allow(Comparison, Ternary) — the operator classification of the
85 // spellings the rows' `under BinaryExpression` / `under TernaryExpression` gates
86 // leave out
87 | Bash::LT | Bash::GT
88 // Bitwise operators
89 | Bash::PIPE | Bash::PIPEAMP
90 | Bash::AMP | Bash::CARET | Bash::TILDE | Bash::BANG
91 | Bash::LTLT | Bash::GTGT
92 // Test operators (prefix)
93 | Bash::DASHa | Bash::DASHo
94 // Redirection operators
95 | Bash::AMPGT | Bash::GTAMP | Bash::LTAMP | Bash::GTPIPE
96 | Bash::LTAMPDASH | Bash::GTAMPDASH | Bash::LTLTDASH | Bash::AMPGTGT
97 | Bash::LTLTLT
98 // `?` for the spelling the `Ternary` row's `under TernaryExpression` gate
99 // leaves out — an expansion's `${y?msg}` — which billed before
100 // the row existed; `QMARK2` is the second `?` id, which no
101 // spelling at the pinned grammar emits.
102 | Bash::QMARK | Bash::QMARK2
103 => TokenRole::Operator,
104
105 // Quoted strings count as one operand when they are inert.
106 // When they contain any `$var`/`${...}`/`$(...)`/`$((...))`
107 // expansion child — the `StringLit` row's `wraps` list — those
108 // expansions are already walked through; only `simple_expansion`
109 // is itself an operand, for the other three it is the leaves
110 // beneath them (`ls` in `$(ls)`, `1` in `$((1))`) that carry
111 // the count, and `${#}` carries none at all. Either way the
112 // wrapping literal must not be counted on top (issue #180).
113 // `RawString` is single-quoted and `AnsiCString` is a leaf
114 // token, so neither can interpolate, but the check is uniform
115 // across the three string kinds for clarity.
116 //
117 // `translated_string` is deliberately absent (#1358) — see the
118 // note on `command_name` below, which it shares a shape with.
119 // role-bypass: allow(StringLit) — the operand classification of the literals
120 // under the row's `wraps` list, a projection the row does not answer
121 Bash::String | Bash::RawString | Bash::AnsiCString => {
122 Self::string_operand_type(node, crate::roles::bash::string_lit::WRAPS)
123 }
124
125 // Operands: identifiers, literals, variables. `variable_name`
126 // and `special_variable_name` each surface under multiple
127 // aliased kind_ids (tree-sitter generates one per parse-table
128 // context); every alias must be matched or assignment LHS
129 // identifiers like `name` in `name=value` are silently
130 // unclassified — see lesson 2.
131 //
132 // `command_name` is deliberately absent (#1351). The grammar
133 // gives it exactly one required child — a `_primary_expression`
134 // or a `concatenation` — and it contributes no text of its own,
135 // so classifying the wrapper *and* letting the walk reach the
136 // child counted every command name twice in N2 (`ls bar` scored
137 // N2 3 for two operands). For a `"$cmd"` command name it also
138 // planted a second vocabulary entry alongside the inner `$cmd`.
139 // Deleting rather than gating is safe here because the wrapper
140 // is never childless and the child kinds are the ordinary
141 // operand kinds; the one residue — a brace `expansion` with no
142 // `variable_name` leaf, `${#}` — scores zero in argument
143 // position too, so the wrapper was masking that gap for command
144 // names alone.
145 //
146 // `translated_string` is absent for the same reason (#1358).
147 // `translated_string: $ => seq('$', $.string)` gives it one
148 // required `string` child and no text of its own beyond the
149 // `$`, so `a=$"x"` scored N2 3 for two operands. It also
150 // defeated the #180 expansion guard: the wrapper's own children
151 // are `$` and `string`, so the `wraps` check never saw the
152 // `simple_expansion` one level down and `b=$"$y"` counted
153 // both `$"$y"` and `$y`.
154 //
155 // The `string` is the keeper because it is the node present for
156 // *every* spelling. Wherever the grammar omits the wrapper — in
157 // ordinary argument position, `echo $"hi"`, which emits a bare
158 // `$` token and a `string` — the child is still there, so
159 // dropping the wrapper makes each position that *does* carry one
160 // (assignment RHS, `case` subject, command name, `for` list,
161 // array element, redirection target, `[[ ]]` operand, and any
162 // other the grammar admits) agree with argument position rather
163 // than newly disagree (grammar-dispatch §6).
164 //
165 // The residue is `command_name`'s, one level down: `$"${#}"`
166 // scores zero, because its inner `string` wraps an operandless
167 // `expansion`. A plain `"${#}"` already scored zero, so that is
168 // the parity rather than a new gap, and
169 // `bash_translated_string_scores_alike_in_both_positions` pins
170 // both halves of it.
171 //
172 // `Checker::is_string` still matches the wrapper, and that is
173 // not drift: `bca find string` reports nodes, and an
174 // interpolating `"$y"` is likewise a string the operand walk
175 // skips.
176 //
177 // `_concat` (`Bash::Concat`) is absent for a different reason:
178 // it is a hidden zero-width external token the scanner emits
179 // between `concatenation` parts, never a named node, and it
180 // spells no operand even if a future grammar promoted it.
181 // Lesson 34 prefers keeping a hidden-rule arm and pinning it,
182 // but keeping this one would preserve a classification that is
183 // wrong the moment it becomes reachable, so the arm goes and
184 // only the marker stays:
185 // `bash_hidden_concat_token_is_unreachable`.
186 Bash::Word | Bash::Word2 | Bash::Word3 | Bash::Word4
187 | Bash::Number | Bash::Number2 | Bash::NumberToken1 | Bash::NumberToken2
188 // role-bypass: allow(StringLit) — the operand classification of an expansion
189 // the `StringLit` row `wraps`, a projection the row does not answer
190 | Bash::SimpleExpansion
191 => TokenRole::Operand,
192
193 // `variable_name` / `special_variable_name` are operands when
194 // they stand alone — the `name` in `name=value`, or the inner
195 // leaf of a brace `${name}` `expansion` whose wrapper is *not*
196 // itself an operand. But `$name` (and `$?`, `$1`, …) parses as a
197 // `simple_expansion` wrapping the same leaf, and `SimpleExpansion`
198 // is already an operand above; counting the inner leaf too would
199 // double-count every bare `$var` reference (inflating n2/N2 and
200 // every derived Halstead value). Exclude the leaf exactly in
201 // that position — the same guard Tcl applies via its anonymous
202 // `Id2` exclusion and iRules applies via a parent check on
203 // `variable_substitution`.
204 Bash::VariableName | Bash::VariableName2 | Bash::VariableName3
205 | Bash::SpecialVariableName | Bash::SpecialVariableName2 => {
206 if ancestors.parent_has_kind(node, Bash::SimpleExpansion as u16) {
207 TokenRole::Unknown
208 } else {
209 TokenRole::Operand
210 }
211 }
212 _ => TokenRole::Unknown,
213 }
214 }
215
216 get_operator!(Bash);
217}