@eslint-sh/eslint-plugin 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/README.md +32 -12
  2. package/dist/api.d.ts +11 -1
  3. package/dist/api.js +8 -0
  4. package/dist/command-harvest/harvest-commands.d.ts +5 -3
  5. package/dist/command-harvest/harvest-commands.js +34 -12
  6. package/dist/eslint-plugin-api.d.ts +65 -12
  7. package/dist/language/command-resolution.d.ts +24 -6
  8. package/dist/language/command-resolution.js +44 -17
  9. package/dist/language/shell-language.js +2 -0
  10. package/dist/language/shell-source-code.d.ts +29 -11
  11. package/dist/language/shell-source-code.js +35 -26
  12. package/dist/language/word-resolution.d.ts +18 -12
  13. package/dist/language/word-resolution.js +133 -3
  14. package/dist/processors/disable-justification.d.ts +20 -0
  15. package/dist/processors/disable-justification.js +124 -0
  16. package/dist/rules/compat/bash-builtin-destination.d.ts +19 -0
  17. package/dist/rules/compat/bash-builtin-destination.js +83 -0
  18. package/dist/rules/compat/declaration-options.d.ts +2 -2
  19. package/dist/rules/compat/declaration-options.js +23 -17
  20. package/dist/rules/compat/no-case-attributes.js +2 -4
  21. package/dist/rules/compat/no-mapfile.js +52 -20
  22. package/dist/rules/compat/no-negative-array-index.d.ts +3 -8
  23. package/dist/rules/compat/no-negative-array-index.js +7 -30
  24. package/dist/rules/compat/no-nounset-empty-array.js +10 -7
  25. package/dist/rules/compat/no-parameter-transformation.js +2 -1
  26. package/dist/rules/compat/no-printf-time-format.js +55 -16
  27. package/dist/rules/compat/no-source.d.ts +3 -8
  28. package/dist/rules/compat/no-source.js +3 -40
  29. package/dist/rules/compat/no-test-v.js +257 -71
  30. package/dist/rules/compat/no-wait-n.js +43 -12
  31. package/dist/rules/compat/nounset-array-proof.d.ts +3 -1
  32. package/dist/rules/compat/nounset-array-proof.js +84 -63
  33. package/dist/rules/compat/posix-absent-command.js +3 -2
  34. package/dist/rules/compat/shopt-options.js +3 -2
  35. package/dist/rules/create-wrapper-rule.js +16 -9
  36. package/dist/rules/no-dynamic-invocation.js +8 -9
  37. package/dist/rules/no-eval.js +19 -8
  38. package/dist/rules/no-masked-exit-status.js +29 -17
  39. package/dist/rules/no-secret-flags.js +4 -3
  40. package/dist/rules/no-unchecked-cd.d.ts +8 -3
  41. package/dist/rules/no-unchecked-cd.js +65 -25
  42. package/dist/rules/no-unused-declarations.js +51 -19
  43. package/dist/rules/prefer-local.js +136 -16
  44. package/dist/rules/require-strict-mode.d.ts +2 -2
  45. package/dist/rules/require-strict-mode.js +27 -18
  46. package/dist/rules/require-tty-guard.d.ts +2 -0
  47. package/dist/rules/require-tty-guard.js +211 -45
  48. package/dist/rules/set-options.d.ts +3 -1
  49. package/dist/rules/set-options.js +5 -1
  50. package/dist/rules/strict-mode-prologue.d.ts +9 -2
  51. package/dist/rules/strict-mode-prologue.js +45 -8
  52. package/docs/custom-rule-tutorial.md +148 -155
  53. package/docs/disable-justification.md +71 -0
  54. package/docs/error-codes.md +4 -0
  55. package/docs/examples/eslint.config.js +11 -0
  56. package/docs/examples/no-curl-in-functions-rule.mjs +20 -23
  57. package/docs/examples/no-listed-commands-rule.ts +19 -19
  58. package/docs/examples/no-rm-rf-rule.mjs +33 -62
  59. package/docs/examples/no-sample-command-rule.mjs +33 -0
  60. package/docs/reading-nodes.md +26 -1
  61. package/docs/rules/README.md +4 -4
  62. package/docs/rules/compat/no-mapfile.md +14 -20
  63. package/docs/rules/compat/no-negative-array-index.md +9 -22
  64. package/docs/rules/compat/no-nounset-empty-array.md +5 -5
  65. package/docs/rules/compat/no-printf-time-format.md +2 -1
  66. package/docs/rules/compat/no-source.md +8 -17
  67. package/docs/rules/compat/no-test-v.md +8 -2
  68. package/docs/rules/compat/no-wait-n.md +3 -1
  69. package/docs/rules/no-dynamic-invocation.md +3 -0
  70. package/docs/rules/no-eval.md +22 -1
  71. package/docs/rules/no-masked-exit-status.md +2 -1
  72. package/docs/rules/no-secret-flags.md +22 -2
  73. package/docs/rules/no-unchecked-cd.md +3 -1
  74. package/docs/rules/no-undeclared-commands.md +1 -1
  75. package/docs/rules/no-unused-declarations.md +10 -6
  76. package/docs/rules/prefer-local.md +4 -0
  77. package/docs/rules/require-network-wrapper.md +1 -1
  78. package/docs/rules/require-strict-mode.md +19 -11
  79. package/docs/rules/require-tty-guard.md +26 -4
  80. package/docs/rules-about-commands.md +78 -0
  81. package/docs/selectors.md +8 -4
  82. package/docs/wrapper-rules.md +1 -1
  83. package/package.json +4 -4
@@ -84,12 +84,15 @@
84
84
  * `-r` (and `readonly` itself) forbids a later assignment, so those forms are
85
85
  * split into the declaration, the assignment, then `readonly <names>`.
86
86
  */
87
+ import { describeWordAtPosition, resolveWordTextAtPosition } from '../language/word-resolution.js';
87
88
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
89
+ import { TsRefVar, TsVarSet } from 'sh-ast';
88
90
  import { resolveTransparentWrappers } from './resolve-transparent-wrappers.js';
89
- import { someShellNode, walkShell } from '../language/syntax-view.js';
91
+ import { definedFunctionNames } from '../command-harvest/harvest-commands.js';
92
+ import { someShellNode } from '../language/syntax-view.js';
90
93
  import { shellLineBreakOf } from '../language/line-breaks.js';
91
94
  import { createRule } from './create-rule.js';
92
- import { batsErrexitIsOn, isStatusChecked } from './no-unchecked-cd.js';
95
+ import { batsErrexitState, isStatusChecked } from './no-unchecked-cd.js';
93
96
  import { setStatementChanges } from './strict-mode-prologue.js';
94
97
  import { applySetOptionChanges, shebangOptionChanges } from './set-options.js';
95
98
  import { BUILTIN_WRAPPER } from './transparent-wrappers.js';
@@ -187,18 +190,10 @@ function insideFunction(node, sourceCode) {
187
190
  * file, so they may read any variable.
188
191
  */
189
192
  const CODE_RUNNING_BUILTINS = new Set(['eval', 'source', '.']);
190
- /** The names of the functions defined anywhere in the file, at any depth. */
191
- function collectFunctionNames(root, into) {
192
- walkShell(root, (node) => {
193
- if (node.type === 'FuncDecl' && node.name !== undefined)
194
- into.add(node.name.value);
195
- });
196
- return into;
197
- }
198
193
  /**
199
194
  * Whether evaluating `node` may run code that reads shell variables without
200
- * showing it: `eval`, `source` / `.`, a command whose name is not static, or
201
- * a call to a function defined in this file. The split moves a declaration
195
+ * showing it: `eval`, `source` / `.`, an unresolved command or operand, or a
196
+ * call to a function defined in this file. The split moves a declaration
202
197
  * earlier, so such code can see a different variable afterwards. A function
203
198
  * defined in another file cannot be seen and is not detected.
204
199
  */
@@ -219,6 +214,20 @@ function runsUnseenCodeHere(node, functionNames, sourceCode, transparentWrappers
219
214
  const name = invoked.effective.text;
220
215
  if (CODE_RUNNING_BUILTINS.has(name) || functionNames.has(name))
221
216
  return true;
217
+ // A computed operand may name a variable that the split declares earlier.
218
+ if (node.args.slice(1).some((word) => {
219
+ const { resolution, fields } = describeWordAtPosition(sourceCode, word);
220
+ return fields.max !== 0 && !resolution.static;
221
+ }))
222
+ return true;
223
+ }
224
+ if (node.type === 'DeclClause') {
225
+ return node.args.some((arg) => arg.name === undefined &&
226
+ arg.value !== undefined &&
227
+ resolveWordTextAtPosition(sourceCode, arg.value) === null);
228
+ }
229
+ if (node.type === 'UnaryTest' && (node.op === TsVarSet || node.op === TsRefVar)) {
230
+ return node.x?.type === 'Word' && resolveWordTextAtPosition(sourceCode, node.x) === null;
222
231
  }
223
232
  return false;
224
233
  }
@@ -273,7 +282,7 @@ function operandsOfDeclClause(node, sourceCode) {
273
282
  let flagsKnown = true;
274
283
  for (const arg of node.args) {
275
284
  if (arg.name === undefined) {
276
- const flag = arg.value === undefined ? null : sourceCode.resolveWordText(arg.value);
285
+ const flag = arg.value === undefined ? null : resolveWordTextAtPosition(sourceCode, arg.value);
277
286
  if (flag === null)
278
287
  flagsKnown = false;
279
288
  else
@@ -373,7 +382,7 @@ function declarationOfWords(variant, words, sourceCode) {
373
382
  });
374
383
  continue;
375
384
  }
376
- const resolved = sourceCode.resolveWordText(word);
385
+ const resolved = resolveWordTextAtPosition(sourceCode, word);
377
386
  if (resolved !== null && VARIABLE_NAME.test(resolved)) {
378
387
  operands.push({
379
388
  node: word,
@@ -413,7 +422,9 @@ const VALID_FLAG_LETTERS = {
413
422
  /** Whether every flag word is a short-option cluster of letters valid for `variant`. */
414
423
  function flagsAreValid(variant, flags) {
415
424
  const letters = VALID_FLAG_LETTERS[variant] ?? '';
416
- return flags.every((flag) => new RegExp(`^-[${letters}]+$`, 'u').test(flag));
425
+ const supported = new RegExp(`^-[${letters}]+$`, 'u');
426
+ const cluster = flags.join('');
427
+ return (flags.every((flag) => supported.test(flag)) && !(cluster.includes('a') && cluster.includes('A')));
417
428
  }
418
429
  /** Whether a flag word is a short-option cluster that includes `-i` (integer). */
419
430
  function isIntegerFlag(flag) {
@@ -570,8 +581,9 @@ const noMaskedExitStatus = createRule({
570
581
  * it on. A function body is read at its definition.
571
582
  */
572
583
  const errexitIsOn = (stmt) => {
573
- if (sourceCode.dialect === 'bats' && batsErrexitIsOn(stmt, parentOf, sourceCode))
584
+ if (sourceCode.dialect === 'bats' && batsErrexitState(stmt, parentOf, sourceCode).enabled) {
574
585
  return true;
586
+ }
575
587
  let topLevel = stmt;
576
588
  for (let up = parentOf(topLevel); up !== undefined && up.type !== 'File'; up = parentOf(up)) {
577
589
  topLevel = up;
@@ -626,7 +638,7 @@ const noMaskedExitStatus = createRule({
626
638
  };
627
639
  return {
628
640
  File(node) {
629
- functionNames = collectFunctionNames(node, new Set());
641
+ functionNames = definedFunctionNames(sourceCode);
630
642
  if (options.onlyWithErrexit === true) {
631
643
  errexitBefore = errexitBeforeEachTopLevelStatement(node, sourceCode, options.allowShebangOnly === true);
632
644
  }
@@ -15,7 +15,7 @@
15
15
  * here-strings, redirect targets, and `[[ … ]]` operands are never argv
16
16
  * words, so they are never matched.
17
17
  * - Whether a word is static is answered only by
18
- * `ShellSourceCode#resolveWordText`. A value is reported only when its
18
+ * the language's position-aware resolver. A value is reported only when its
19
19
  * whole word resolves statically; any expansion, substitution, glob, or
20
20
  * other dynamic part makes it fine.
21
21
  * - Matching is a name pattern, not secret detection. The default pattern
@@ -25,6 +25,7 @@
25
25
  * (`--password-stdin`, `--token-file`). Other names that only look secret
26
26
  * can still match; the `patterns` option replaces the list.
27
27
  */
28
+ import { resolveWordTextAtPosition } from '../language/word-resolution.js';
28
29
  import { createRule } from './create-rule.js';
29
30
  import { compileUserPattern } from './user-pattern.js';
30
31
  /**
@@ -134,7 +135,7 @@ export const noSecretFlags = createRule({
134
135
  const word = args.at(i);
135
136
  if (word === undefined)
136
137
  continue;
137
- const text = sourceCode.resolveWordText(word);
138
+ const text = resolveWordTextAtPosition(sourceCode, word);
138
139
  if (text === null)
139
140
  continue;
140
141
  const { name, value } = splitFlagWord(text);
@@ -149,7 +150,7 @@ export const noSecretFlags = createRule({
149
150
  // `--flag value` across two words: the next word is the value when it
150
151
  // is static and not itself a flag.
151
152
  const next = args.at(i + 1);
152
- const nextText = next === undefined ? null : sourceCode.resolveWordText(next);
153
+ const nextText = next === undefined ? null : resolveWordTextAtPosition(sourceCode, next);
153
154
  if (next !== undefined && nextText !== null && isLiteralValueWord(nextText)) {
154
155
  findings.push({ flag: name, start: word, end: next });
155
156
  i++; // the value word is consumed; it is not a flag in its own right
@@ -19,10 +19,15 @@ export type NoUncheckedCdMessageId = 'uncheckedCd' | 'appendExit';
19
19
  * @internal
20
20
  */
21
21
  export declare function isStatusChecked(stmt: ShellNodeOf<'Stmt'>, parentOf: (node: ShellNode) => ShellNode | undefined): boolean;
22
+ /** The state from recognized option changes and whether an unresolved option could alter it. @internal */
23
+ export interface ErrexitState {
24
+ readonly enabled: boolean;
25
+ readonly uncertain: boolean;
26
+ }
22
27
  /**
23
- * Whether bats' `errexit` is still in force when `stmt` runs, for a statement
28
+ * The known and unresolved changes to bats' `errexit`, for a statement
24
29
  * written directly in a bats `@test` body or top-level hook, or directly in a
25
- * `( … )` subshell that is itself such a statement. `false` for every other
30
+ * `( … )` subshell that is itself such a statement. Disabled for every other
26
31
  * position, and for a statement `errexit` ignores (negated or in the
27
32
  * background).
28
33
  *
@@ -39,6 +44,6 @@ export declare function isStatusChecked(stmt: ShellNodeOf<'Stmt'>, parentOf: (no
39
44
  *
40
45
  * @internal
41
46
  */
42
- export declare function batsErrexitIsOn(stmt: ShellNodeOf<'Stmt'>, parentOf: (node: ShellNode) => ShellNode | undefined, sourceCode: ShellSourceCode): boolean;
47
+ export declare function batsErrexitState(stmt: ShellNodeOf<'Stmt'>, parentOf: (node: ShellNode) => ShellNode | undefined, sourceCode: ShellSourceCode): ErrexitState;
43
48
  /** Built-in rule `sh/no-unchecked-cd`. @internal */
44
49
  export declare const noUncheckedCd: import("./define-shell-rule.js").ShellRule<[NoUncheckedCdOptions], NoUncheckedCdMessageId>;
@@ -23,7 +23,7 @@
23
23
  * arms, pipelines and background jobs never check on their own.
24
24
  *
25
25
  * A file whose prologue enables `errexit` (the same reading `require-strict-mode`
26
- * uses, via `prologueEnabledOptions`) aborts on a failed `cd` by itself, so the
26
+ * uses, via `prologueOptionState`) aborts on a failed `cd` by itself, so the
27
27
  * rule stays quiet there unless `ignoreWhenErrexit` is `false`.
28
28
  *
29
29
  * Under `dialect: "bats"` the bodies of `@test` blocks and of the file's
@@ -36,7 +36,7 @@
36
36
  * any statement nested in an `if`, loop or `case`, a `$( … )` substitution, and
37
37
  * any dialect other than `bats` is read as before. `run cd x` is unaffected:
38
38
  * `run` is not a wrapper this rule follows, so the command it sees is `run`,
39
- * not `cd`. See `batsErrexitIsOn` for what the rule cannot see.
39
+ * not `cd`. See `batsErrexitState` for what the rule cannot see.
40
40
  *
41
41
  * The command is recognized as the effective command after transparent
42
42
  * wrappers, so `builtin cd x` and `command cd x` are read as `cd`.
@@ -46,11 +46,15 @@
46
46
  * `&&`/`||`/pipeline (appending would change what the rest of the list does),
47
47
  * negated, in the background, or carrying a here-document (the text after the
48
48
  * statement is the document body, not shell code).
49
+ * It is also withheld when the file may install an error trap (`trap … ERR`,
50
+ * Zsh's `trap … ZERR` or a `TRAPZERR` function): the trap does not run for
51
+ * the left side of `||`, so the edit would silence it.
49
52
  */
50
53
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
51
54
  import { resolveTransparentWrappers } from './resolve-transparent-wrappers.js';
55
+ import { someShellNode } from '../language/syntax-view.js';
52
56
  import { createRule } from './create-rule.js';
53
- import { prologueEnabledOptions, resolveStrictModePrologue, setStatementChanges, } from './strict-mode-prologue.js';
57
+ import { prologueOptionState, resolveStrictModePrologue, setStatementArguments, } from './strict-mode-prologue.js';
54
58
  import { BUILTIN_WRAPPER } from './transparent-wrappers.js';
55
59
  /** The commands that change the working directory and can fail doing so. */
56
60
  const DIRECTORY_COMMANDS = new Set(['cd', 'pushd', 'popd']);
@@ -113,10 +117,11 @@ export function isStatusChecked(stmt, parentOf) {
113
117
  current = enclosing;
114
118
  }
115
119
  }
120
+ const NO_ERREXIT = { enabled: false, uncertain: false };
116
121
  /**
117
- * Whether bats' `errexit` is still in force when `stmt` runs, for a statement
122
+ * The known and unresolved changes to bats' `errexit`, for a statement
118
123
  * written directly in a bats `@test` body or top-level hook, or directly in a
119
- * `( … )` subshell that is itself such a statement. `false` for every other
124
+ * `( … )` subshell that is itself such a statement. Disabled for every other
120
125
  * position, and for a statement `errexit` ignores (negated or in the
121
126
  * background).
122
127
  *
@@ -133,49 +138,57 @@ export function isStatusChecked(stmt, parentOf) {
133
138
  *
134
139
  * @internal
135
140
  */
136
- export function batsErrexitIsOn(stmt, parentOf, sourceCode) {
141
+ export function batsErrexitState(stmt, parentOf, sourceCode) {
137
142
  if (stmt.background || stmt.negated)
138
- return false;
143
+ return NO_ERREXIT;
139
144
  const container = parentOf(stmt);
140
145
  let siblings;
141
- let enabled;
146
+ let enabled = true;
147
+ let uncertain = false;
142
148
  if (container?.type === 'Block') {
143
149
  const bodyStmt = parentOf(container);
144
150
  const decl = bodyStmt === undefined ? undefined : parentOf(bodyStmt);
145
151
  if (decl === undefined || !('body' in decl) || decl.body !== bodyStmt)
146
- return false;
152
+ return NO_ERREXIT;
147
153
  if (decl.type === 'FuncDecl') {
148
154
  const declStmt = parentOf(decl);
149
155
  const name = decl.name?.value;
150
156
  if (name === undefined || !BATS_ERREXIT_HOOKS.has(name))
151
- return false;
157
+ return NO_ERREXIT;
152
158
  if (declStmt === undefined || parentOf(declStmt)?.type !== 'File')
153
- return false;
159
+ return NO_ERREXIT;
154
160
  }
155
161
  siblings = container.stmts;
156
- enabled = true;
157
162
  }
158
163
  else if (container?.type === 'Subshell') {
159
164
  const subshellStmt = parentOf(container);
160
165
  if (subshellStmt?.type !== 'Stmt' || subshellStmt.cmd !== container)
161
- return false;
162
- if (!batsErrexitIsOn(subshellStmt, parentOf, sourceCode))
163
- return false;
166
+ return NO_ERREXIT;
167
+ const inherited = batsErrexitState(subshellStmt, parentOf, sourceCode);
168
+ if (!inherited.enabled)
169
+ return inherited;
170
+ uncertain = inherited.uncertain;
164
171
  siblings = container.stmts;
165
- enabled = true;
166
172
  }
167
173
  else {
168
- return false;
174
+ return NO_ERREXIT;
169
175
  }
170
176
  for (const earlier of siblings) {
171
177
  if (earlier === stmt)
172
178
  break;
173
- for (const { option, enable } of setStatementChanges(earlier, sourceCode)) {
174
- if (option === 'errexit')
179
+ const parsed = setStatementArguments(earlier, sourceCode);
180
+ if (parsed === undefined)
181
+ continue;
182
+ for (const { option, enable } of parsed.changes) {
183
+ if (option === 'errexit') {
175
184
  enabled = enable;
185
+ uncertain = false;
186
+ }
176
187
  }
188
+ if (parsed.stoppedBy === 'unknown')
189
+ uncertain = true;
177
190
  }
178
- return enabled;
191
+ return { enabled, uncertain };
179
192
  }
180
193
  /**
181
194
  * The index just past the command and its redirections, excluding the
@@ -213,11 +226,31 @@ export const noUncheckedCd = createRule({
213
226
  const prologue = resolveStrictModePrologue(context.settings);
214
227
  const transparentWrappers = resolveTransparentWrappers(context, TRANSPARENT_WRAPPERS);
215
228
  let errexitInForce = false;
229
+ let errexitUncertain = false;
230
+ let hasErrorTrap = false;
216
231
  return {
217
232
  File(node) {
218
- errexitInForce =
219
- options.ignoreWhenErrexit !== false &&
220
- prologueEnabledOptions(node, sourceCode, prologue).has('errexit');
233
+ if (sourceCode.dialect !== 'posix') {
234
+ hasErrorTrap = sourceCode.getCommandInventory().commands.some((site) => {
235
+ const { effective, chainIndices } = site.resolveInvokedCommand({ transparentWrappers });
236
+ return ((!effective.static || effective.text === 'trap') &&
237
+ site.argv
238
+ .slice((chainIndices.at(-1) ?? 0) + 1)
239
+ .some((word) => !word.static || /^(?:SIG)?(?:ERR|ZERR)$/iu.test(word.text)));
240
+ });
241
+ }
242
+ // Zsh also runs a function named TRAPZERR on failure; defining it,
243
+ // directly or through the `functions` parameter, installs the trap.
244
+ if (sourceCode.dialect === 'zsh' && !hasErrorTrap) {
245
+ hasErrorTrap = someShellNode(node, (part) => part.type === 'FuncDecl'
246
+ ? [part.name, ...part.names].some((name) => name?.value === 'TRAPZERR')
247
+ : part.type === 'Assign' && part.name?.value === 'functions');
248
+ }
249
+ if (options.ignoreWhenErrexit === false)
250
+ return;
251
+ const { enabled, hasUnknownOptions } = prologueOptionState(node, sourceCode, prologue);
252
+ errexitInForce = enabled.has('errexit');
253
+ errexitUncertain = hasUnknownOptions;
221
254
  },
222
255
  CallExpr(node) {
223
256
  if (errexitInForce)
@@ -235,11 +268,18 @@ export const noUncheckedCd = createRule({
235
268
  const parentOf = (n) => sourceCode.getParent(n);
236
269
  if (isStatusChecked(stmt, parentOf))
237
270
  return;
238
- if (sourceCode.dialect === 'bats' && batsErrexitIsOn(stmt, parentOf, sourceCode))
271
+ const batsErrexit = sourceCode.dialect === 'bats' ? batsErrexitState(stmt, parentOf, sourceCode) : NO_ERREXIT;
272
+ if (batsErrexit.enabled)
239
273
  return;
240
274
  const container = parentOf(stmt);
241
275
  const hasHeredoc = stmt.redirs.some((r) => r.hdoc !== undefined);
242
- const canAppend = !stmt.background && !stmt.negated && !hasHeredoc && container?.type !== 'BinaryCmd';
276
+ const canAppend = !errexitUncertain &&
277
+ !hasErrorTrap &&
278
+ !batsErrexit.uncertain &&
279
+ !stmt.background &&
280
+ !stmt.negated &&
281
+ !hasHeredoc &&
282
+ container?.type !== 'BinaryCmd';
243
283
  context.report({
244
284
  node,
245
285
  messageId: 'uncheckedCd',
@@ -1,6 +1,7 @@
1
1
  import { resolveTransparentWrappers } from './resolve-transparent-wrappers.js';
2
2
  import { functionNames, harvestCommands } from '../command-harvest/harvest-commands.js';
3
3
  import { harvestWrapperTable } from '../command-harvest/wrapper-table.js';
4
+ import { commandBasename } from '../language/command-resolution.js';
4
5
  import { createRule } from './create-rule.js';
5
6
  import { getDeclaredCommands } from '../declaration-conventions/get-declared-commands.js';
6
7
  import { resolveDeclarationConvention } from './resolve-declaration-convention.js';
@@ -129,10 +130,14 @@ const COMMAND_STRING_CLUSTER = /^-[A-Za-z]*c[A-Za-z]*$/u;
129
130
  * shell never becomes the effective command. Matching the words directly
130
131
  * catches them without modeling each command's options.
131
132
  */
132
- function passesShellCommandString(argv) {
133
- const shellIndex = argv.findIndex((word, index) => index > 0 && word.static && SHELL_NAMES.has(pathBasename(word.text) ?? word.text));
133
+ function passesShellCommandString(site) {
134
+ const shellIndex = site.argvFacts.findIndex(({ basename }, index) => index > 0 && basename.known && SHELL_NAMES.has(basename.text));
134
135
  return (shellIndex !== -1 &&
135
- argv.slice(shellIndex + 1).some((word) => word.static && COMMAND_STRING_CLUSTER.test(word.text)));
136
+ site.argvFacts
137
+ .slice(shellIndex + 1)
138
+ .some((facts) => facts.resolution.static
139
+ ? COMMAND_STRING_CLUSTER.test(facts.resolution.text)
140
+ : facts.fields.max !== 0));
136
141
  }
137
142
  /**
138
143
  * Whether `site` may run code that cannot be read from the source:
@@ -148,10 +153,13 @@ function passesShellCommandString(argv) {
148
153
  * is still the effective command reads its code from standard input
149
154
  * (`curl x | bash`, `bash < script`, `bash -s`).
150
155
  */
151
- function runsUnknownCode(site, resolution) {
156
+ function runsUnknownCode(site, resolution, wrapperBasenames) {
152
157
  const { effective, chainIndices } = resolution;
153
- if (!effective.static)
154
- return true;
158
+ if (!effective.static) {
159
+ const index = chainIndices.at(-1);
160
+ const base = index === undefined ? null : commandBasename(site, effective, index);
161
+ return base === null || wrapperBasenames.has(base);
162
+ }
155
163
  const { text } = effective;
156
164
  if (text === 'eval')
157
165
  return true;
@@ -161,7 +169,12 @@ function runsUnknownCode(site, resolution) {
161
169
  return false;
162
170
  // `chainIndices` locates the effective command in argv; its operands follow it.
163
171
  const effectiveIndex = chainIndices.at(-1);
164
- const operands = effectiveIndex === undefined ? [] : site.argv.slice(effectiveIndex + 1);
172
+ const operands = effectiveIndex === undefined
173
+ ? []
174
+ : site.argvFacts
175
+ .slice(effectiveIndex + 1)
176
+ .filter(({ fields }) => fields.max !== 0)
177
+ .map(({ resolution }) => resolution);
165
178
  return text === 'trap' ? trapSetsCodeString(operands) : operands.length > 0;
166
179
  }
167
180
  /** `text`, and also its basename when `text` is a path (contains a slash). */
@@ -175,7 +188,7 @@ function topLevelFunctionEnds(sourceCode) {
175
188
  for (const stmt of sourceCode.ast.stmts) {
176
189
  if (stmt.cmd?.type !== 'FuncDecl' || stmt.background || stmt.coprocess || stmt.disown)
177
190
  continue;
178
- for (const name of functionNames(stmt.cmd)) {
191
+ for (const name of functionNames(sourceCode, stmt.cmd)) {
179
192
  if (!ends.has(name))
180
193
  ends.set(name, stmt.range[1]);
181
194
  }
@@ -232,6 +245,7 @@ export const noUnusedDeclarations = createRule({
232
245
  ];
233
246
  // Bound once so the hook keeps its convention as `this`, however it is written.
234
247
  const removeDeclaration = convention.removeDeclaration?.bind(convention);
248
+ const wrapperBasenames = new Set(completenessWrappers.flatMap((wrapper) => wrapper.names.map((name) => pathBasename(name) ?? name)));
235
249
  return {
236
250
  File() {
237
251
  const inventory = sourceCode.getCommandInventory();
@@ -240,17 +254,40 @@ export const noUnusedDeclarations = createRule({
240
254
  return;
241
255
  }
242
256
  const sites = inventory.commands;
257
+ const used = new Set();
258
+ const possiblePaths = new Set();
243
259
  let mayRemoveFunctions = false;
244
260
  for (const site of sites) {
245
- if (passesShellCommandString(site.argv))
261
+ // Any argument can name a program that the command runs. An unresolved
262
+ // word can still have a matching basename even when only its directory varies.
263
+ for (const { resolution, basename, fields } of site.argvFacts.slice(1)) {
264
+ if (fields.max === 0)
265
+ continue;
266
+ if (resolution.static) {
267
+ used.add(resolution.text);
268
+ if (basename.known)
269
+ used.add(basename.text);
270
+ }
271
+ else {
272
+ if (!basename.known)
273
+ return;
274
+ possiblePaths.add(basename.text);
275
+ }
276
+ }
277
+ if (passesShellCommandString(site))
246
278
  return;
247
279
  const resolution = resolveEffective(site, completenessWrappers);
248
- if (runsUnknownCode(site, resolution))
280
+ if (runsUnknownCode(site, resolution, wrapperBasenames))
249
281
  return;
282
+ if (!resolution.effective.static) {
283
+ const index = resolution.chainIndices.at(-1);
284
+ const base = index === undefined ? null : commandBasename(site, resolution.effective, index);
285
+ if (base !== null)
286
+ possiblePaths.add(base);
287
+ }
250
288
  // A removal in a function or a trap can happen at a later call site.
251
289
  mayRemoveFunctions ||= canRemoveFunctions(site, resolution, sourceCode.dialect);
252
290
  }
253
- const used = new Set();
254
291
  const functionEnds = mayRemoveFunctions ? undefined : topLevelFunctionEnds(sourceCode);
255
292
  const harvest = harvestCommands(sourceCode, {
256
293
  transparentWrappers,
@@ -267,20 +304,15 @@ export const noUnusedDeclarations = createRule({
267
304
  for (const each of namesFor(name))
268
305
  used.add(each);
269
306
  }
270
- for (const site of sites) {
271
- for (const word of site.argv.slice(1)) {
272
- if (word.static)
273
- for (const each of namesFor(word.text))
274
- used.add(each);
275
- }
276
- }
277
307
  const declarations = getDeclaredCommands(context);
278
308
  if (declarations === null) {
279
309
  return;
280
310
  }
281
311
  for (const declared of declarations) {
282
- if (used.has(declared.name))
312
+ if (used.has(declared.name) ||
313
+ possiblePaths.has(pathBasename(declared.name) ?? declared.name)) {
283
314
  continue;
315
+ }
284
316
  if (declared.kind === 'script') {
285
317
  context.report({
286
318
  loc: {