@eslint-sh/eslint-plugin 0.12.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 (71) 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 +5 -3
  4. package/dist/command-harvest/harvest-commands.js +34 -12
  5. package/dist/eslint-plugin-api.d.ts +25 -11
  6. package/dist/language/command-resolution.d.ts +16 -6
  7. package/dist/language/command-resolution.js +44 -17
  8. package/dist/language/shell-source-code.d.ts +18 -10
  9. package/dist/language/shell-source-code.js +24 -25
  10. package/dist/language/word-resolution.d.ts +18 -12
  11. package/dist/language/word-resolution.js +133 -3
  12. package/dist/rules/compat/bash-builtin-destination.d.ts +2 -0
  13. package/dist/rules/compat/bash-builtin-destination.js +4 -0
  14. package/dist/rules/compat/declaration-options.d.ts +2 -2
  15. package/dist/rules/compat/declaration-options.js +23 -17
  16. package/dist/rules/compat/no-case-attributes.js +2 -4
  17. package/dist/rules/compat/no-mapfile.js +16 -19
  18. package/dist/rules/compat/no-negative-array-index.d.ts +3 -8
  19. package/dist/rules/compat/no-negative-array-index.js +7 -30
  20. package/dist/rules/compat/no-nounset-empty-array.js +10 -7
  21. package/dist/rules/compat/no-parameter-transformation.js +2 -1
  22. package/dist/rules/compat/no-printf-time-format.js +38 -16
  23. package/dist/rules/compat/no-source.d.ts +3 -8
  24. package/dist/rules/compat/no-source.js +3 -40
  25. package/dist/rules/compat/no-test-v.js +243 -61
  26. package/dist/rules/compat/no-wait-n.js +43 -12
  27. package/dist/rules/compat/nounset-array-proof.d.ts +3 -1
  28. package/dist/rules/compat/nounset-array-proof.js +84 -63
  29. package/dist/rules/compat/posix-absent-command.js +3 -2
  30. package/dist/rules/compat/shopt-options.js +3 -2
  31. package/dist/rules/create-wrapper-rule.js +16 -9
  32. package/dist/rules/no-dynamic-invocation.js +8 -9
  33. package/dist/rules/no-eval.js +19 -8
  34. package/dist/rules/no-masked-exit-status.js +29 -17
  35. package/dist/rules/no-secret-flags.js +4 -3
  36. package/dist/rules/no-unchecked-cd.d.ts +8 -3
  37. package/dist/rules/no-unchecked-cd.js +54 -25
  38. package/dist/rules/no-unused-declarations.js +51 -19
  39. package/dist/rules/prefer-local.js +136 -16
  40. package/dist/rules/require-strict-mode.d.ts +2 -2
  41. package/dist/rules/require-strict-mode.js +27 -18
  42. package/dist/rules/require-tty-guard.d.ts +2 -0
  43. package/dist/rules/require-tty-guard.js +197 -45
  44. package/dist/rules/set-options.d.ts +3 -1
  45. package/dist/rules/set-options.js +5 -1
  46. package/dist/rules/strict-mode-prologue.d.ts +9 -2
  47. package/dist/rules/strict-mode-prologue.js +45 -8
  48. package/docs/custom-rule-tutorial.md +10 -7
  49. package/docs/error-codes.md +4 -0
  50. package/docs/examples/no-curl-in-functions-rule.mjs +7 -5
  51. package/docs/rules/README.md +4 -4
  52. package/docs/rules/compat/no-mapfile.md +11 -20
  53. package/docs/rules/compat/no-negative-array-index.md +9 -22
  54. package/docs/rules/compat/no-nounset-empty-array.md +5 -5
  55. package/docs/rules/compat/no-printf-time-format.md +2 -1
  56. package/docs/rules/compat/no-source.md +8 -17
  57. package/docs/rules/compat/no-test-v.md +7 -1
  58. package/docs/rules/compat/no-wait-n.md +3 -1
  59. package/docs/rules/no-dynamic-invocation.md +3 -0
  60. package/docs/rules/no-eval.md +22 -1
  61. package/docs/rules/no-masked-exit-status.md +2 -1
  62. package/docs/rules/no-secret-flags.md +22 -2
  63. package/docs/rules/no-unchecked-cd.md +2 -1
  64. package/docs/rules/no-undeclared-commands.md +1 -1
  65. package/docs/rules/no-unused-declarations.md +10 -6
  66. package/docs/rules/prefer-local.md +4 -0
  67. package/docs/rules/require-network-wrapper.md +1 -1
  68. package/docs/rules/require-strict-mode.md +19 -11
  69. package/docs/rules/require-tty-guard.md +26 -4
  70. package/docs/wrapper-rules.md +1 -1
  71. package/package.json +4 -4
@@ -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,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: {
@@ -1,3 +1,44 @@
1
+ /**
2
+ * `sh/prefer-local`: a variable assigned inside a function must be declared
3
+ * `local` (or `declare`/`typeset`) in that function, so the function does not
4
+ * overwrite a global its caller may depend on. Shell variables are global by
5
+ * default, and a helper that assigns `i`, `tmp` or `result` silently corrupts
6
+ * the same-named variable of every caller.
7
+ *
8
+ * **What counts as an assignment** inside a function body:
9
+ *
10
+ * - a plain assignment statement (`x=1`, `x+=1`, `x=$(cmd)`); an assignment
11
+ * that prefixes a command (`x=1 cmd`) only reaches that command's
12
+ * environment and is not reported;
13
+ * - the variables named by `read` (`read -r a b`, `read -a arr`);
14
+ * - the loop variable of `for x in …` / `select x in …`.
15
+ *
16
+ * **What is exempt:** a name that is declared `local`, `declare` or `typeset`
17
+ * earlier in the function; a name assigned at top level before the function is
18
+ * defined (an intentional global); a name declared with `declare -g`/
19
+ * `typeset -g` or by `export`/`readonly` (an explicit global); and a name the
20
+ * `allow` option lists or the `allowPattern` option matches (UPPER_CASE
21
+ * globals by default). Each function is its own scope: nested function
22
+ * definitions are checked on their own, and subshells, command substitutions
23
+ * and process substitutions are skipped because their assignments cannot leak.
24
+ * So is every element of a pipeline (`cmd | read x`, `ls | while read l; …`):
25
+ * pipeline elements run in subshells, except that the last one runs in the
26
+ * current shell when the file enables `shopt -s lastpipe`.
27
+ * A function whose body is a subshell (`f() ( … )`) is skipped for the same
28
+ * reason.
29
+ *
30
+ * Only the first assignment to a name in a function is reported: the
31
+ * declaration that fixes it covers the rest.
32
+ *
33
+ * Adding a local declaration can change reads through dynamic scope and
34
+ * which writes remain visible to the caller. Choosing that scope is a manual
35
+ * edit.
36
+ *
37
+ * `local` is not POSIX, so the rule is inert under `dialect: "posix"`.
38
+ *
39
+ * The language resolves command names and words in their AST positions.
40
+ */
41
+ import { resolveWordTextAtPosition } from '../language/word-resolution.js';
1
42
  import { childNodes, walkShell } from '../language/syntax-view.js';
2
43
  import { createRule } from './create-rule.js';
3
44
  import { compileUserPattern } from './user-pattern.js';
@@ -23,18 +64,24 @@ const READ_OPTIONS_WITH_ARGUMENT = new Set([
23
64
  * the rest of the cluster, or else the next word. `-a`'s array name is an
24
65
  * ordinary target word. Words that are not static are not guessed at.
25
66
  */
26
- function readTargets(args, sourceCode) {
67
+ function readTargets(args, sourceCode, canReadCoprocess) {
27
68
  const targets = [];
28
69
  let optionsEnded = false;
29
- let nextIsOptionArgument = false;
70
+ let argumentTo;
71
+ const unprovenMkshCoprocess = sourceCode.dialect === 'mksh' && !canReadCoprocess;
30
72
  for (const word of args.slice(1)) {
31
- const text = sourceCode.resolveWordText(word);
32
- if (nextIsOptionArgument) {
33
- nextIsOptionArgument = false;
73
+ const text = resolveWordTextAtPosition(sourceCode, word);
74
+ if (argumentTo !== undefined) {
75
+ if (unprovenMkshCoprocess && argumentTo === 'u' && (text === null || text === 'p'))
76
+ return [];
77
+ argumentTo = undefined;
34
78
  continue;
35
79
  }
36
- if (text === null)
80
+ if (text === null) {
81
+ if (unprovenMkshCoprocess && !optionsEnded)
82
+ return [];
37
83
  continue;
84
+ }
38
85
  if (!optionsEnded && text === '--') {
39
86
  optionsEnded = true;
40
87
  continue;
@@ -42,8 +89,15 @@ function readTargets(args, sourceCode) {
42
89
  if (!optionsEnded && text.startsWith('-') && text.length > 1) {
43
90
  for (let index = 1; index < text.length; index += 1) {
44
91
  const letter = text.charAt(index);
45
- if (READ_OPTIONS_WITH_ARGUMENT.has(letter)) {
46
- nextIsOptionArgument = index === text.length - 1;
92
+ const coprocess = letter === 'p' && (sourceCode.dialect === 'zsh' || sourceCode.dialect === 'mksh');
93
+ if (coprocess && !canReadCoprocess)
94
+ return [];
95
+ if (!coprocess && READ_OPTIONS_WITH_ARGUMENT.has(letter)) {
96
+ const attached = text.slice(index + 1);
97
+ if (unprovenMkshCoprocess && letter === 'u' && attached === 'p')
98
+ return [];
99
+ if (attached === '')
100
+ argumentTo = letter;
47
101
  break;
48
102
  }
49
103
  }
@@ -59,7 +113,7 @@ function readTargets(args, sourceCode) {
59
113
  * `declare`/`typeset` with a `-g` flag, and every non-scoped declaration
60
114
  * (`export`, `readonly`), bind their names as intentional globals.
61
115
  */
62
- function bindingsOf(node, sourceCode) {
116
+ function bindingsOf(node, sourceCode, coprocessReads) {
63
117
  if (node.type === 'ForClause') {
64
118
  const { loop } = node;
65
119
  if (loop?.type !== 'WordIter' || loop.name === undefined)
@@ -72,13 +126,15 @@ function bindingsOf(node, sourceCode) {
72
126
  ? []
73
127
  : [{ name: assign.name.value, kind: 'assign', node: assign }]);
74
128
  }
75
- return sourceCode.getCommandName(node) === 'read' ? readTargets(node.args, sourceCode) : [];
129
+ return sourceCode.getCommandName(node) === 'read'
130
+ ? readTargets(node.args, sourceCode, sourceCode.dialect !== 'mksh' || coprocessReads.has(node))
131
+ : [];
76
132
  }
77
133
  if (node.type === 'DeclClause') {
78
134
  const variant = node.variant?.value;
79
135
  const flags = node.args
80
136
  .filter((arg) => arg.naked && arg.name === undefined && arg.value !== undefined)
81
- .map((arg) => (arg.value === undefined ? null : sourceCode.resolveWordText(arg.value)));
137
+ .map((arg) => arg.value === undefined ? null : resolveWordTextAtPosition(sourceCode, arg.value));
82
138
  const isGlobal = variant === undefined ||
83
139
  !SCOPED_DECLARATIONS.has(variant) ||
84
140
  flags.some((flag) => flag !== null && /^-[A-Za-z]*g/u.test(flag));
@@ -114,12 +170,75 @@ function enablesLastpipe(root, sourceCode) {
114
170
  walkShell(root, (node) => {
115
171
  if (node.type !== 'CallExpr' || sourceCode.getCommandName(node) !== 'shopt')
116
172
  return;
117
- const words = node.args.slice(1).map((word) => sourceCode.resolveWordText(word));
173
+ const words = node.args.slice(1).map((word) => resolveWordTextAtPosition(sourceCode, word));
118
174
  if (words.includes('-s') && words.includes('lastpipe'))
119
175
  enabled = true;
120
176
  });
121
177
  return enabled;
122
178
  }
179
+ /** An unconditional statement in the current shell, with no redirection to set up. */
180
+ function plainStatement(stmt) {
181
+ return !stmt.background && !stmt.disown && !stmt.negated && stmt.redirs.length === 0;
182
+ }
183
+ /**
184
+ * mksh starts with no coprocess. A direct launch can supply a following read
185
+ * before an intervening command can replace or consume its pipe. Follow only
186
+ * the first command of a directly invoked function, and stop at opaque code.
187
+ */
188
+ function provenMkshCoprocessReads(source) {
189
+ const reads = new Set();
190
+ const functions = new Map();
191
+ if (source.dialect !== 'mksh')
192
+ return reads;
193
+ function literalCall(stmt) {
194
+ if (stmt === undefined || !plainStatement(stmt) || stmt.cmd?.type !== 'CallExpr')
195
+ return undefined;
196
+ const call = stmt.cmd;
197
+ return call.assigns.length === 0 &&
198
+ call.args.every((word) => resolveWordTextAtPosition(source, word) !== null)
199
+ ? call
200
+ : undefined;
201
+ }
202
+ let live = false;
203
+ for (const stmt of source.ast.stmts) {
204
+ if (!plainStatement(stmt))
205
+ break;
206
+ if (!stmt.coprocess && stmt.cmd?.type === 'FuncDecl') {
207
+ const { name, body } = stmt.cmd;
208
+ if (name === undefined || body === undefined)
209
+ break;
210
+ functions.set(name.value, body);
211
+ continue;
212
+ }
213
+ const call = literalCall(stmt);
214
+ if (call === undefined)
215
+ break;
216
+ if (stmt.coprocess) {
217
+ live = true;
218
+ continue;
219
+ }
220
+ const name = source.getCommandName(call);
221
+ if (name === null)
222
+ break;
223
+ const body = functions.get(name);
224
+ if (body === undefined || !plainStatement(body) || body.coprocess)
225
+ break;
226
+ const statements = body.cmd?.type === 'Block' ? body.cmd.stmts : [body];
227
+ const first = statements.at(0);
228
+ const startsCoprocess = (first?.coprocess ?? false) && literalCall(first) !== undefined;
229
+ const readStatement = statements[startsCoprocess ? 1 : 0];
230
+ const read = literalCall(readStatement);
231
+ if ((live || startsCoprocess) &&
232
+ read !== undefined &&
233
+ !readStatement.coprocess &&
234
+ source.getCommandName(read) === 'read' &&
235
+ !functions.has('read')) {
236
+ reads.add(read);
237
+ }
238
+ break;
239
+ }
240
+ return reads;
241
+ }
123
242
  /**
124
243
  * Every binding in `root`'s own scope, in source order. Nested function
125
244
  * definitions and isolated scopes (subshells, substitutions, background jobs)
@@ -127,7 +246,7 @@ function enablesLastpipe(root, sourceCode) {
127
246
  * Pipeline elements run in subshells, so only the last element of a pipeline
128
247
  * is entered, and only when `lastpipe` is enabled.
129
248
  */
130
- function scopeBindings(root, sourceCode, lastpipe) {
249
+ function scopeBindings(root, sourceCode, lastpipe, coprocessReads) {
131
250
  const found = [];
132
251
  // Pre-order with an explicit stack: children are pushed in reverse so they pop in source order.
133
252
  const pending = [root];
@@ -141,7 +260,7 @@ function scopeBindings(root, sourceCode, lastpipe) {
141
260
  pending.push(node.y);
142
261
  continue;
143
262
  }
144
- found.push(...bindingsOf(node, sourceCode));
263
+ found.push(...bindingsOf(node, sourceCode, coprocessReads));
145
264
  const children = childNodes(node);
146
265
  for (let index = children.length - 1; index >= 0; index--)
147
266
  pending.push(children[index]);
@@ -182,6 +301,7 @@ const preferLocal = createRule({
182
301
  if (sourceCode.dialect === 'posix')
183
302
  return {};
184
303
  const lastpipe = enablesLastpipe(sourceCode.ast, sourceCode);
304
+ const coprocessReads = provenMkshCoprocessReads(sourceCode);
185
305
  // Names assigned or declared outside every function, with where each
186
306
  // binding ends: assigned before a function is defined, they are globals
187
307
  // the function is meant to share.
@@ -189,7 +309,7 @@ const preferLocal = createRule({
189
309
  let topLevelCollected = false;
190
310
  const topLevelBefore = (position) => {
191
311
  if (!topLevelCollected) {
192
- topLevelBindings.push(...scopeBindings(sourceCode.ast, sourceCode, lastpipe));
312
+ topLevelBindings.push(...scopeBindings(sourceCode.ast, sourceCode, lastpipe, coprocessReads));
193
313
  topLevelCollected = true;
194
314
  }
195
315
  return new Set(topLevelBindings.filter((b) => b.node.range[1] <= position).map((b) => b.name));
@@ -202,7 +322,7 @@ const preferLocal = createRule({
202
322
  const global = topLevelBefore(func.range[0]);
203
323
  const declared = new Set();
204
324
  const functionName = func.name?.value ?? '';
205
- for (const binding of scopeBindings(body, sourceCode, lastpipe)) {
325
+ for (const binding of scopeBindings(body, sourceCode, lastpipe, coprocessReads)) {
206
326
  const { name } = binding;
207
327
  if (binding.kind !== 'assign') {
208
328
  declared.add(name);
@@ -3,9 +3,9 @@ export interface RequireStrictModeOptions {
3
3
  /**
4
4
  * Nonempty, unique long option names from the existing `set -o` domain.
5
5
  * When absent, POSIX requires errexit/nounset and other dialects also require
6
- * pipefail. The formatter, rather than consumer text, owns autofix spelling.
6
+ * pipefail. The formatter, rather than consumer text, owns the inserted spelling.
7
7
  */
8
8
  readonly requiredOptions?: readonly string[];
9
9
  }
10
10
  /** Built-in rule `sh/require-strict-mode`. @internal */
11
- export declare const requireStrictMode: import("./define-shell-rule.js").ShellRule<[RequireStrictModeOptions], "missingStrictMode">;
11
+ export declare const requireStrictMode: import("./define-shell-rule.js").ShellRule<[RequireStrictModeOptions], "missingStrictMode" | "enableStrictMode">;