@eslint-sh/eslint-plugin 0.11.0 → 0.13.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 (84) hide show
  1. package/README.md +5 -2
  2. package/dist/api.d.ts +1 -1
  3. package/dist/command-harvest/harvest-commands.d.ts +10 -4
  4. package/dist/command-harvest/harvest-commands.js +39 -10
  5. package/dist/eslint-plugin-api.d.ts +36 -14
  6. package/dist/language/command-resolution.d.ts +16 -6
  7. package/dist/language/command-resolution.js +44 -17
  8. package/dist/language/line-breaks.d.ts +10 -4
  9. package/dist/language/line-breaks.js +14 -5
  10. package/dist/language/shell-language.d.ts +2 -0
  11. package/dist/language/shell-language.js +10 -1
  12. package/dist/language/shell-source-code.d.ts +29 -13
  13. package/dist/language/shell-source-code.js +126 -55
  14. package/dist/language/word-resolution.d.ts +18 -12
  15. package/dist/language/word-resolution.js +133 -3
  16. package/dist/rules/compat/bash-builtin-destination.d.ts +2 -0
  17. package/dist/rules/compat/bash-builtin-destination.js +4 -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 +16 -19
  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 +38 -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 +243 -61
  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 +34 -46
  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 +54 -25
  42. package/dist/rules/no-unused-declarations.js +127 -30
  43. package/dist/rules/prefer-local.js +146 -52
  44. package/dist/rules/require-shebang.js +23 -21
  45. package/dist/rules/require-strict-mode.d.ts +2 -2
  46. package/dist/rules/require-strict-mode.js +28 -16
  47. package/dist/rules/require-tty-guard.d.ts +2 -0
  48. package/dist/rules/require-tty-guard.js +205 -50
  49. package/dist/rules/set-options.d.ts +5 -16
  50. package/dist/rules/set-options.js +17 -45
  51. package/dist/rules/shebang-interpreter.d.ts +33 -10
  52. package/dist/rules/shebang-interpreter.js +522 -53
  53. package/dist/rules/shebang-matches-dialect.js +4 -4
  54. package/dist/rules/strict-mode-prologue.d.ts +9 -2
  55. package/dist/rules/strict-mode-prologue.js +45 -8
  56. package/dist/rules/variable-reads.d.ts +12 -0
  57. package/dist/rules/variable-reads.js +31 -0
  58. package/docs/custom-rule-tutorial.md +19 -10
  59. package/docs/error-codes.md +6 -1
  60. package/docs/examples/no-curl-in-functions-rule.mjs +7 -5
  61. package/docs/rules/README.md +5 -5
  62. package/docs/rules/compat/no-mapfile.md +11 -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 +7 -1
  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 +4 -1
  72. package/docs/rules/no-secret-flags.md +22 -2
  73. package/docs/rules/no-unchecked-cd.md +2 -1
  74. package/docs/rules/no-undeclared-commands.md +1 -1
  75. package/docs/rules/no-unused-declarations.md +18 -9
  76. package/docs/rules/prefer-local.md +15 -33
  77. package/docs/rules/require-network-wrapper.md +1 -1
  78. package/docs/rules/require-shebang.md +46 -3
  79. package/docs/rules/require-strict-mode.md +40 -15
  80. package/docs/rules/require-tty-guard.md +27 -4
  81. package/docs/rules/shebang-matches-dialect.md +3 -0
  82. package/docs/shellcheck.md +1 -1
  83. package/docs/wrapper-rules.md +1 -1
  84. package/package.json +4 -4
@@ -84,15 +84,19 @@
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';
90
- import { lineBreakOf } from '../language/line-breaks.js';
91
+ import { definedFunctionNames } from '../command-harvest/harvest-commands.js';
92
+ import { someShellNode } from '../language/syntax-view.js';
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';
99
+ import { mentionsIdentifier, readsNameHere } from './variable-reads.js';
96
100
  /** Every declaration builtin the rule can check; the default for `builtins`. */
97
101
  const ALL_BUILTINS = ['local', 'declare', 'typeset', 'export', 'readonly'];
98
102
  /** The builtins that create a variable in the enclosing function's scope. */
@@ -157,10 +161,6 @@ export function containsCommandSubstitution(root) {
157
161
  return node.type === 'ProcSubst' ? 'skip' : false;
158
162
  });
159
163
  }
160
- /** Whether `text` mentions `name` as a whole identifier. */
161
- function mentionsIdentifier(text, name) {
162
- return new RegExp(`(?<![A-Za-z0-9_])${name}(?![A-Za-z0-9_])`, 'u').test(text);
163
- }
164
164
  /**
165
165
  * Whether evaluating `node` reads any of `names`: a parameter expansion of
166
166
  * the name (`$x`, `${x:-…}`, `${a[x]}`), or an arithmetic expansion that
@@ -174,27 +174,6 @@ function readsAnyName(root, names, sourceCode) {
174
174
  return false;
175
175
  return someShellNode(root, (node) => readsNameHere(node, names, sourceCode));
176
176
  }
177
- /** Whether `node` itself, not its descendants, reads any of `names`. */
178
- function readsNameHere(node, names, sourceCode) {
179
- if (node.type === 'ParamExp') {
180
- if (node.excl)
181
- return true;
182
- const param = node.param?.value;
183
- if (param !== undefined && names.includes(param))
184
- return true;
185
- if (node.index !== undefined) {
186
- const indexText = sourceCode.text.slice(node.index.range[0], node.index.range[1]);
187
- if (names.some((name) => mentionsIdentifier(indexText, name)))
188
- return true;
189
- }
190
- }
191
- if (node.type === 'ArithmExp' || node.type === 'ArithmCmd') {
192
- const arithmetic = sourceCode.text.slice(node.range[0], node.range[1]);
193
- if (names.some((name) => mentionsIdentifier(arithmetic, name)))
194
- return true;
195
- }
196
- return false;
197
- }
198
177
  /**
199
178
  * Whether `node` sits inside a function body: a function definition or a bats
200
179
  * `@test` block, which bats runs as a function.
@@ -211,18 +190,10 @@ function insideFunction(node, sourceCode) {
211
190
  * file, so they may read any variable.
212
191
  */
213
192
  const CODE_RUNNING_BUILTINS = new Set(['eval', 'source', '.']);
214
- /** The names of the functions defined anywhere in the file, at any depth. */
215
- function collectFunctionNames(root, into) {
216
- walkShell(root, (node) => {
217
- if (node.type === 'FuncDecl' && node.name !== undefined)
218
- into.add(node.name.value);
219
- });
220
- return into;
221
- }
222
193
  /**
223
194
  * Whether evaluating `node` may run code that reads shell variables without
224
- * showing it: `eval`, `source` / `.`, a command whose name is not static, or
225
- * 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
226
197
  * earlier, so such code can see a different variable afterwards. A function
227
198
  * defined in another file cannot be seen and is not detected.
228
199
  */
@@ -243,6 +214,20 @@ function runsUnseenCodeHere(node, functionNames, sourceCode, transparentWrappers
243
214
  const name = invoked.effective.text;
244
215
  if (CODE_RUNNING_BUILTINS.has(name) || functionNames.has(name))
245
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;
246
231
  }
247
232
  return false;
248
233
  }
@@ -297,7 +282,7 @@ function operandsOfDeclClause(node, sourceCode) {
297
282
  let flagsKnown = true;
298
283
  for (const arg of node.args) {
299
284
  if (arg.name === undefined) {
300
- const flag = arg.value === undefined ? null : sourceCode.resolveWordText(arg.value);
285
+ const flag = arg.value === undefined ? null : resolveWordTextAtPosition(sourceCode, arg.value);
301
286
  if (flag === null)
302
287
  flagsKnown = false;
303
288
  else
@@ -397,7 +382,7 @@ function declarationOfWords(variant, words, sourceCode) {
397
382
  });
398
383
  continue;
399
384
  }
400
- const resolved = sourceCode.resolveWordText(word);
385
+ const resolved = resolveWordTextAtPosition(sourceCode, word);
401
386
  if (resolved !== null && VARIABLE_NAME.test(resolved)) {
402
387
  operands.push({
403
388
  node: word,
@@ -437,7 +422,9 @@ const VALID_FLAG_LETTERS = {
437
422
  /** Whether every flag word is a short-option cluster of letters valid for `variant`. */
438
423
  function flagsAreValid(variant, flags) {
439
424
  const letters = VALID_FLAG_LETTERS[variant] ?? '';
440
- 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')));
441
428
  }
442
429
  /** Whether a flag word is a short-option cluster that includes `-i` (integer). */
443
430
  function isIntegerFlag(flag) {
@@ -594,8 +581,9 @@ const noMaskedExitStatus = createRule({
594
581
  * it on. A function body is read at its definition.
595
582
  */
596
583
  const errexitIsOn = (stmt) => {
597
- if (sourceCode.dialect === 'bats' && batsErrexitIsOn(stmt, parentOf, sourceCode))
584
+ if (sourceCode.dialect === 'bats' && batsErrexitState(stmt, parentOf, sourceCode).enabled) {
598
585
  return true;
586
+ }
599
587
  let topLevel = stmt;
600
588
  for (let up = parentOf(topLevel); up !== undefined && up.type !== 'File'; up = parentOf(up)) {
601
589
  topLevel = up;
@@ -625,9 +613,9 @@ const noMaskedExitStatus = createRule({
625
613
  if (offerSuggestion && validHere && isStandalone(stmt, sourceCode)) {
626
614
  const text = sourceCode.text;
627
615
  const start = node.range[0];
628
- const lineStart = Math.max(text.lastIndexOf('\n', start - 1), text.lastIndexOf('\r', start - 1));
629
- const indent = text.slice(lineStart + 1, start);
630
- const separator = /^[ \t]*$/u.test(indent) ? lineBreakOf(text) + indent : '; ';
616
+ const lineStart = text.lastIndexOf('\n', start - 1) + 1;
617
+ const indent = text.slice(lineStart, start);
618
+ const separator = /^[ \t]*$/u.test(indent) ? shellLineBreakOf(text, start) + indent : '; ';
631
619
  const scoped = SCOPED_BUILTINS.has(builtin) && inFunction;
632
620
  suggestion = splitText(declaration, scoped, separator, functionNames, sourceCode, transparentWrappers);
633
621
  }
@@ -650,7 +638,7 @@ const noMaskedExitStatus = createRule({
650
638
  };
651
639
  return {
652
640
  File(node) {
653
- functionNames = collectFunctionNames(node, new Set());
641
+ functionNames = definedFunctionNames(sourceCode);
654
642
  if (options.onlyWithErrexit === true) {
655
643
  errexitBefore = errexitBeforeEachTopLevelStatement(node, sourceCode, options.allowShebangOnly === true);
656
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`.
@@ -50,7 +50,7 @@
50
50
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
51
51
  import { resolveTransparentWrappers } from './resolve-transparent-wrappers.js';
52
52
  import { createRule } from './create-rule.js';
53
- import { prologueEnabledOptions, resolveStrictModePrologue, setStatementChanges, } from './strict-mode-prologue.js';
53
+ import { prologueOptionState, resolveStrictModePrologue, setStatementArguments, } from './strict-mode-prologue.js';
54
54
  import { BUILTIN_WRAPPER } from './transparent-wrappers.js';
55
55
  /** The commands that change the working directory and can fail doing so. */
56
56
  const DIRECTORY_COMMANDS = new Set(['cd', 'pushd', 'popd']);
@@ -113,10 +113,11 @@ export function isStatusChecked(stmt, parentOf) {
113
113
  current = enclosing;
114
114
  }
115
115
  }
116
+ const NO_ERREXIT = { enabled: false, uncertain: false };
116
117
  /**
117
- * Whether bats' `errexit` is still in force when `stmt` runs, for a statement
118
+ * The known and unresolved changes to bats' `errexit`, for a statement
118
119
  * 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
120
+ * `( … )` subshell that is itself such a statement. Disabled for every other
120
121
  * position, and for a statement `errexit` ignores (negated or in the
121
122
  * background).
122
123
  *
@@ -133,49 +134,57 @@ export function isStatusChecked(stmt, parentOf) {
133
134
  *
134
135
  * @internal
135
136
  */
136
- export function batsErrexitIsOn(stmt, parentOf, sourceCode) {
137
+ export function batsErrexitState(stmt, parentOf, sourceCode) {
137
138
  if (stmt.background || stmt.negated)
138
- return false;
139
+ return NO_ERREXIT;
139
140
  const container = parentOf(stmt);
140
141
  let siblings;
141
- let enabled;
142
+ let enabled = true;
143
+ let uncertain = false;
142
144
  if (container?.type === 'Block') {
143
145
  const bodyStmt = parentOf(container);
144
146
  const decl = bodyStmt === undefined ? undefined : parentOf(bodyStmt);
145
147
  if (decl === undefined || !('body' in decl) || decl.body !== bodyStmt)
146
- return false;
148
+ return NO_ERREXIT;
147
149
  if (decl.type === 'FuncDecl') {
148
150
  const declStmt = parentOf(decl);
149
151
  const name = decl.name?.value;
150
152
  if (name === undefined || !BATS_ERREXIT_HOOKS.has(name))
151
- return false;
153
+ return NO_ERREXIT;
152
154
  if (declStmt === undefined || parentOf(declStmt)?.type !== 'File')
153
- return false;
155
+ return NO_ERREXIT;
154
156
  }
155
157
  siblings = container.stmts;
156
- enabled = true;
157
158
  }
158
159
  else if (container?.type === 'Subshell') {
159
160
  const subshellStmt = parentOf(container);
160
161
  if (subshellStmt?.type !== 'Stmt' || subshellStmt.cmd !== container)
161
- return false;
162
- if (!batsErrexitIsOn(subshellStmt, parentOf, sourceCode))
163
- return false;
162
+ return NO_ERREXIT;
163
+ const inherited = batsErrexitState(subshellStmt, parentOf, sourceCode);
164
+ if (!inherited.enabled)
165
+ return inherited;
166
+ uncertain = inherited.uncertain;
164
167
  siblings = container.stmts;
165
- enabled = true;
166
168
  }
167
169
  else {
168
- return false;
170
+ return NO_ERREXIT;
169
171
  }
170
172
  for (const earlier of siblings) {
171
173
  if (earlier === stmt)
172
174
  break;
173
- for (const { option, enable } of setStatementChanges(earlier, sourceCode)) {
174
- if (option === 'errexit')
175
+ const parsed = setStatementArguments(earlier, sourceCode);
176
+ if (parsed === undefined)
177
+ continue;
178
+ for (const { option, enable } of parsed.changes) {
179
+ if (option === 'errexit') {
175
180
  enabled = enable;
181
+ uncertain = false;
182
+ }
176
183
  }
184
+ if (parsed.stoppedBy === 'unknown')
185
+ uncertain = true;
177
186
  }
178
- return enabled;
187
+ return { enabled, uncertain };
179
188
  }
180
189
  /**
181
190
  * The index just past the command and its redirections, excluding the
@@ -213,11 +222,24 @@ export const noUncheckedCd = createRule({
213
222
  const prologue = resolveStrictModePrologue(context.settings);
214
223
  const transparentWrappers = resolveTransparentWrappers(context, TRANSPARENT_WRAPPERS);
215
224
  let errexitInForce = false;
225
+ let errexitUncertain = false;
226
+ let hasErrorTrap = false;
216
227
  return {
217
228
  File(node) {
218
- errexitInForce =
219
- options.ignoreWhenErrexit !== false &&
220
- prologueEnabledOptions(node, sourceCode, prologue).has('errexit');
229
+ if (sourceCode.dialect !== 'posix') {
230
+ hasErrorTrap = sourceCode.getCommandInventory().commands.some((site) => {
231
+ const { effective, chainIndices } = site.resolveInvokedCommand({ transparentWrappers });
232
+ return ((!effective.static || effective.text === 'trap') &&
233
+ site.argv
234
+ .slice((chainIndices.at(-1) ?? 0) + 1)
235
+ .some((word) => !word.static || /^(?:SIG)?(?:ERR|ZERR)$/iu.test(word.text)));
236
+ });
237
+ }
238
+ if (options.ignoreWhenErrexit === false)
239
+ return;
240
+ const { enabled, hasUnknownOptions } = prologueOptionState(node, sourceCode, prologue);
241
+ errexitInForce = enabled.has('errexit');
242
+ errexitUncertain = hasUnknownOptions;
221
243
  },
222
244
  CallExpr(node) {
223
245
  if (errexitInForce)
@@ -235,11 +257,18 @@ export const noUncheckedCd = createRule({
235
257
  const parentOf = (n) => sourceCode.getParent(n);
236
258
  if (isStatusChecked(stmt, parentOf))
237
259
  return;
238
- if (sourceCode.dialect === 'bats' && batsErrexitIsOn(stmt, parentOf, sourceCode))
260
+ const batsErrexit = sourceCode.dialect === 'bats' ? batsErrexitState(stmt, parentOf, sourceCode) : NO_ERREXIT;
261
+ if (batsErrexit.enabled)
239
262
  return;
240
263
  const container = parentOf(stmt);
241
264
  const hasHeredoc = stmt.redirs.some((r) => r.hdoc !== undefined);
242
- const canAppend = !stmt.background && !stmt.negated && !hasHeredoc && container?.type !== 'BinaryCmd';
265
+ const canAppend = !errexitUncertain &&
266
+ !hasErrorTrap &&
267
+ !batsErrexit.uncertain &&
268
+ !stmt.background &&
269
+ !stmt.negated &&
270
+ !hasHeredoc &&
271
+ container?.type !== 'BinaryCmd';
243
272
  context.report({
244
273
  node,
245
274
  messageId: 'uncheckedCd',
@@ -1,10 +1,11 @@
1
1
  import { resolveTransparentWrappers } from './resolve-transparent-wrappers.js';
2
- import { harvestCommands } from '../command-harvest/harvest-commands.js';
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';
7
- import { SHELL_WRAPPER } from './transparent-wrappers.js';
8
+ import { BUILTIN_WRAPPER, SHELL_WRAPPER } from './transparent-wrappers.js';
8
9
  /** The registry name of this rule (`sh/no-unused-declarations` in a user's config). */
9
10
  const RULE_NAME = 'no-unused-declarations';
10
11
  /**
@@ -82,6 +83,41 @@ function resolveEffective(site, table) {
82
83
  current = [{ ...spec, names: [path] }, ...current];
83
84
  }
84
85
  }
86
+ /** Whether a resolved command can remove a function from command lookup. */
87
+ function canRemoveFunctions(site, resolution, dialect) {
88
+ const { effective, chainIndices } = resolution;
89
+ if (!effective.static)
90
+ return false;
91
+ const command = effective.text;
92
+ if (dialect === 'zsh' && command === 'unfunction')
93
+ return true;
94
+ if (command !== 'unset' && !(dialect === 'zsh' && command === 'disable'))
95
+ return false;
96
+ let flags = '';
97
+ const args = site.argv.slice((chainIndices.at(-1) ?? 0) + 1);
98
+ let index = 0;
99
+ let unknownOptions = false;
100
+ for (; index < args.length; index++) {
101
+ const word = args[index];
102
+ if (!word.static) {
103
+ unknownOptions = true;
104
+ break;
105
+ }
106
+ if (word.text === '--') {
107
+ index++;
108
+ break;
109
+ }
110
+ if (!/^-[a-z]+$/iu.test(word.text))
111
+ break;
112
+ flags += word.text.slice(1);
113
+ }
114
+ if (index === args.length)
115
+ return false;
116
+ // Bash rejects combining -v with -f, including when an expansion supplies -f.
117
+ if (command === 'unset' && dialect === 'bash' && flags.includes('v'))
118
+ return false;
119
+ return unknownOptions || flags.includes('f') || (command === 'unset' && !flags.includes('v'));
120
+ }
85
121
  /** A short-option cluster that includes `c` (`-c`, `-ec`, `-xc`): a shell's command-string flag. */
86
122
  const COMMAND_STRING_CLUSTER = /^-[A-Za-z]*c[A-Za-z]*$/u;
87
123
  /**
@@ -94,10 +130,14 @@ const COMMAND_STRING_CLUSTER = /^-[A-Za-z]*c[A-Za-z]*$/u;
94
130
  * shell never becomes the effective command. Matching the words directly
95
131
  * catches them without modeling each command's options.
96
132
  */
97
- function passesShellCommandString(argv) {
98
- 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));
99
135
  return (shellIndex !== -1 &&
100
- 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));
101
141
  }
102
142
  /**
103
143
  * Whether `site` may run code that cannot be read from the source:
@@ -111,19 +151,15 @@ function passesShellCommandString(argv) {
111
151
  * With {@link SHELL_WRAPPER} followed, a script operand would be the
112
152
  * effective command and `-c` would be an embedded command, so a shell that
113
153
  * is still the effective command reads its code from standard input
114
- * (`curl x | bash`, `bash < script`, `bash -s`);
115
- * - it hands a command string to a shell named in its arguments (see
116
- * {@link passesShellCommandString}).
117
- *
118
- * `completenessWrappers` is the table to follow (see the rule's `create`).
154
+ * (`curl x | bash`, `bash < script`, `bash -s`).
119
155
  */
120
- function runsUnknownCode(site, completenessWrappers) {
121
- if (passesShellCommandString(site.argv))
122
- return true;
123
- const resolution = resolveEffective(site, completenessWrappers);
156
+ function runsUnknownCode(site, resolution, wrapperBasenames) {
124
157
  const { effective, chainIndices } = resolution;
125
- if (!effective.static)
126
- 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
+ }
127
163
  const { text } = effective;
128
164
  if (text === 'eval')
129
165
  return true;
@@ -133,7 +169,12 @@ function runsUnknownCode(site, completenessWrappers) {
133
169
  return false;
134
170
  // `chainIndices` locates the effective command in argv; its operands follow it.
135
171
  const effectiveIndex = chainIndices.at(-1);
136
- 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);
137
178
  return text === 'trap' ? trapSetsCodeString(operands) : operands.length > 0;
138
179
  }
139
180
  /** `text`, and also its basename when `text` is a path (contains a slash). */
@@ -141,6 +182,19 @@ function namesFor(text) {
141
182
  const base = pathBasename(text);
142
183
  return base === null ? [text] : [text, base];
143
184
  }
185
+ /** Only direct, synchronous top-level definitions give us a source-order guarantee. */
186
+ function topLevelFunctionEnds(sourceCode) {
187
+ const ends = new Map();
188
+ for (const stmt of sourceCode.ast.stmts) {
189
+ if (stmt.cmd?.type !== 'FuncDecl' || stmt.background || stmt.coprocess || stmt.disown)
190
+ continue;
191
+ for (const name of functionNames(sourceCode, stmt.cmd)) {
192
+ if (!ends.has(name))
193
+ ends.set(name, stmt.range[1]);
194
+ }
195
+ }
196
+ return ends;
197
+ }
144
198
  /**
145
199
  * How a report names where an out-of-script declaration lives: `path:line`
146
200
  * (or `path` when the line is unknown) for a file, the description for a
@@ -178,15 +232,20 @@ export const noUnusedDeclarations = createRule({
178
232
  }
179
233
  const { sourceCode } = context;
180
234
  const transparentWrappers = resolveTransparentWrappers(context, harvestWrapperTable(sourceCode.dialect));
181
- // The completeness check follows the harvest's table plus shells
235
+ // The completeness check follows the harvest's table plus `builtin` and shells
182
236
  // invoked as commands, so `bash -c '…'` and `sh -c '…'` resolve to an
183
237
  // embedded command (as in `no-dynamic-invocation`) instead of stopping
184
238
  // at the shell. `env -S` is already embedded in the defaults. Path
185
239
  // forms (`/bin/bash`, `/usr/bin/env`) are followed per site by
186
240
  // `resolveEffective`.
187
- const completenessWrappers = [...transparentWrappers, SHELL_WRAPPER];
241
+ const completenessWrappers = [
242
+ ...transparentWrappers,
243
+ BUILTIN_WRAPPER,
244
+ SHELL_WRAPPER,
245
+ ];
188
246
  // Bound once so the hook keeps its convention as `this`, however it is written.
189
247
  const removeDeclaration = convention.removeDeclaration?.bind(convention);
248
+ const wrapperBasenames = new Set(completenessWrappers.flatMap((wrapper) => wrapper.names.map((name) => pathBasename(name) ?? name)));
190
249
  return {
191
250
  File() {
192
251
  const inventory = sourceCode.getCommandInventory();
@@ -195,27 +254,65 @@ export const noUnusedDeclarations = createRule({
195
254
  return;
196
255
  }
197
256
  const sites = inventory.commands;
198
- if (sites.some((site) => runsUnknownCode(site, completenessWrappers)))
199
- return;
200
257
  const used = new Set();
201
- for (const name of harvestCommands(sourceCode, { transparentWrappers }).commands.keys()) {
202
- for (const each of namesFor(name))
203
- used.add(each);
204
- }
258
+ const possiblePaths = new Set();
259
+ let mayRemoveFunctions = false;
205
260
  for (const site of sites) {
206
- for (const word of site.argv.slice(1)) {
207
- if (word.static)
208
- for (const each of namesFor(word.text))
209
- used.add(each);
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
+ }
210
276
  }
277
+ if (passesShellCommandString(site))
278
+ return;
279
+ const resolution = resolveEffective(site, completenessWrappers);
280
+ if (runsUnknownCode(site, resolution, wrapperBasenames))
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
+ }
288
+ // A removal in a function or a trap can happen at a later call site.
289
+ mayRemoveFunctions ||= canRemoveFunctions(site, resolution, sourceCode.dialect);
290
+ }
291
+ const functionEnds = mayRemoveFunctions ? undefined : topLevelFunctionEnds(sourceCode);
292
+ const harvest = harvestCommands(sourceCode, {
293
+ transparentWrappers,
294
+ excludeFunction(name, site) {
295
+ const end = functionEnds?.get(name);
296
+ if (end === undefined || end > site.node.range[0])
297
+ return false;
298
+ // A nested call can run earlier than its source position suggests.
299
+ const stmt = sourceCode.getParent(site.node);
300
+ return stmt?.type === 'Stmt' && sourceCode.getParent(stmt) === sourceCode.ast;
301
+ },
302
+ });
303
+ for (const name of harvest.commands.keys()) {
304
+ for (const each of namesFor(name))
305
+ used.add(each);
211
306
  }
212
307
  const declarations = getDeclaredCommands(context);
213
308
  if (declarations === null) {
214
309
  return;
215
310
  }
216
311
  for (const declared of declarations) {
217
- if (used.has(declared.name))
312
+ if (used.has(declared.name) ||
313
+ possiblePaths.has(pathBasename(declared.name) ?? declared.name)) {
218
314
  continue;
315
+ }
219
316
  if (declared.kind === 'script') {
220
317
  context.report({
221
318
  loc: {