@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
@@ -11,12 +11,17 @@
11
11
  * apparent assignment may fail, write through another name, or evaluate arithmetic. Unknown means
12
12
  * report, never assume safety from source order across execution boundaries.
13
13
  */
14
+ import { describeWordAtPosition, isSingleField, resolveWordTextAtPosition, } from '../../language/word-resolution.js';
14
15
  import { AndStmt, AssignUnset, AssignUnsetOrNull, TsEql, TsGeq, TsGtr, TsLeq, TsLss, TsNeq, TsVarSet, } from 'sh-ast';
15
16
  import { walkShell } from '../../language/syntax-view.js';
16
- import { parseSetArguments } from '../set-options.js';
17
+ import { parseSetWords } from '../strict-mode-prologue.js';
17
18
  import { hasSpecialBashIntegerSetter } from '../bash-variable-semantics.js';
18
19
  /** No local evidence is available on an unexamined execution path. */
19
- const UNKNOWN = { nounsetOff: false, nonEmpty: new Set() };
20
+ const UNKNOWN = { nounsetOff: 'unproven', nonEmpty: new Map() };
21
+ /** Locale and tilde uncertainty can obscure text even when the word survives as a field. */
22
+ function hasLocaleOrTildeUncertainty(resolution) {
23
+ return !resolution.static && (resolution.reason === 'locale' || resolution.reason === 'tilde');
24
+ }
20
25
  /** These commands can install effects that outlive a later simple assignment. */
21
26
  const DYNAMIC_ENVIRONMENT = new Set([
22
27
  'eval',
@@ -158,7 +163,7 @@ export function createArraySafetyProof(source) {
158
163
  dynamicEnvironment = true;
159
164
  }
160
165
  if (node.type === 'CallExpr' && node.args.length > 0) {
161
- const args = node.args.map((word) => source.resolveWordText(word));
166
+ const args = node.args.map((word) => resolveWordTextAtPosition(source, word));
162
167
  let index = 0;
163
168
  // Wrappers do not make dynamic code or attribute writes transparent.
164
169
  while (args[index] === 'builtin' || args[index] === 'command') {
@@ -217,7 +222,7 @@ export function createArraySafetyProof(source) {
217
222
  if (arg.name !== undefined) {
218
223
  return !IDENTIFIER.test(arg.name.value);
219
224
  }
220
- const text = arg.value === undefined ? null : source.resolveWordText(arg.value);
225
+ const text = arg.value === undefined ? null : resolveWordTextAtPosition(source, arg.value);
221
226
  // A naked declaration word can introduce options or an assignment at runtime.
222
227
  return (text === null ||
223
228
  (text !== '--' && !/^[-+][A-Za-z]+$/u.test(text)) ||
@@ -278,7 +283,7 @@ export function createArraySafetyProof(source) {
278
283
  /** Literal integers and direct array lengths cannot recursively evaluate variable text. */
279
284
  function simpleArithmetic(node) {
280
285
  return (lengthName(node) !== undefined ||
281
- (node?.type === 'Word' && /^\d+$/u.test(source.resolveWordText(node) ?? '')));
286
+ (node?.type === 'Word' && /^\d+$/u.test(resolveWordTextAtPosition(source, node) ?? '')));
282
287
  }
283
288
  /** Only ordinary destinations and known string formats rule out persistent printf writes. */
284
289
  function inertPrintf(args) {
@@ -304,47 +309,26 @@ export function createArraySafetyProof(source) {
304
309
  (ended || !format.startsWith('-')) &&
305
310
  INERT_PRINTF_FORMAT.test(format));
306
311
  }
307
- /** A quoted scalar is one test operand; array/positional @ expansions can inject operators. */
308
- function singleTestArgument(word) {
309
- if (source.resolveWordText(word) !== null) {
310
- return true;
311
- }
312
- if (word.parts.length !== 1 || word.parts[0].type !== 'DblQuoted' || word.parts[0].dollar) {
313
- return false;
314
- }
315
- let single = true;
316
- walkShell(word.parts[0], (part) => {
317
- if (part.type === 'ParamExp' &&
318
- !part.length &&
319
- (part.param?.value === '@' ||
320
- (part.index !== undefined &&
321
- wholeArrayIndex(part.index) &&
322
- source.getText(part.index) === '@'))) {
323
- single = false;
324
- }
325
- });
326
- return single;
327
- }
328
312
  /** Fixed test operators plus one-word operands exclude hidden -v/-R variable-name evaluation. */
329
313
  function inertTest(name, words) {
330
314
  const args = [...words];
331
315
  if (name === '[') {
332
316
  const close = args.at(-1);
333
- if (close === undefined || source.resolveWordText(close) !== ']') {
317
+ if (close === undefined || resolveWordTextAtPosition(source, close) !== ']') {
334
318
  return false;
335
319
  }
336
320
  args.pop();
337
321
  }
338
- if (!args.every(singleTestArgument)) {
322
+ if (!args.every((word) => isSingleField(describeWordAtPosition(source, word)))) {
339
323
  return false;
340
324
  }
341
325
  if (args.length < 2) {
342
326
  return true;
343
327
  }
344
328
  if (args.length === 2) {
345
- return INERT_TEST_UNARY.has(source.resolveWordText(args[0]) ?? '');
329
+ return INERT_TEST_UNARY.has(resolveWordTextAtPosition(source, args[0]) ?? '');
346
330
  }
347
- return args.length === 3 && INERT_TEST_BINARY.has(source.resolveWordText(args[1]) ?? '');
331
+ return (args.length === 3 && INERT_TEST_BINARY.has(resolveWordTextAtPosition(source, args[1]) ?? ''));
348
332
  }
349
333
  /** Exact zero/nonzero length predicates, with no other commands or arithmetic. */
350
334
  function testedArray(stmt, empty) {
@@ -357,16 +341,16 @@ export function createArraySafetyProof(source) {
357
341
  const args = cmd.args.slice(1);
358
342
  if (name === '[' &&
359
343
  args.length > 0 &&
360
- source.resolveWordText(args[args.length - 1]) === ']') {
344
+ resolveWordTextAtPosition(source, args[args.length - 1]) === ']') {
361
345
  args.pop();
362
346
  }
363
347
  else if (name !== 'test') {
364
348
  return undefined;
365
349
  }
366
- if (args.length !== 3 || source.resolveWordText(args[2]) !== '0') {
350
+ if (args.length !== 3 || resolveWordTextAtPosition(source, args[2]) !== '0') {
367
351
  return undefined;
368
352
  }
369
- const op = source.resolveWordText(args[1]);
353
+ const op = resolveWordTextAtPosition(source, args[1]);
370
354
  if (empty ? op !== '-eq' : op !== '-gt' && op !== '-ne') {
371
355
  return undefined;
372
356
  }
@@ -374,7 +358,7 @@ export function createArraySafetyProof(source) {
374
358
  }
375
359
  if (cmd?.type === 'TestClause' && cmd.x?.type === 'BinaryTest') {
376
360
  const { op, x, y } = cmd.x;
377
- if (y?.type !== 'Word' || source.resolveWordText(y) !== '0') {
361
+ if (y?.type !== 'Word' || resolveWordTextAtPosition(source, y) !== '0') {
378
362
  return undefined;
379
363
  }
380
364
  if (empty ? op !== TsEql : op !== TsGtr && op !== TsNeq) {
@@ -400,7 +384,8 @@ export function createArraySafetyProof(source) {
400
384
  if (cmd.args.length > 2) {
401
385
  return false;
402
386
  }
403
- if (cmd.args.length === 2 && !/^\d{1,3}$/u.test(source.resolveWordText(cmd.args[1]) ?? '')) {
387
+ if (cmd.args.length === 2 &&
388
+ !/^\d{1,3}$/u.test(resolveWordTextAtPosition(source, cmd.args[1]) ?? '')) {
404
389
  return false;
405
390
  }
406
391
  if (name === 'exit') {
@@ -417,16 +402,25 @@ export function createArraySafetyProof(source) {
417
402
  * Literal members cannot disappear through splitting or nullglob. Quoted empty
418
403
  * strings count as members; an unquoted pattern or a computed word does not.
419
404
  */
420
- function literalArray(assign) {
421
- return (!variableAttributes &&
422
- assign.name?.value !== 'FUNCNAME' &&
423
- !assign.append &&
424
- assign.index === undefined &&
425
- assign.array !== undefined &&
426
- assign.array.elems.length > 0 &&
427
- assign.array.elems.every((elem) => elem.index === undefined &&
428
- elem.value !== undefined &&
429
- source.resolveWordText(elem.value) !== null));
405
+ function arrayMemberEvidence(assign) {
406
+ if (variableAttributes ||
407
+ assign.name?.value === 'FUNCNAME' ||
408
+ assign.append ||
409
+ assign.index !== undefined ||
410
+ assign.array === undefined ||
411
+ assign.array.elems.length === 0) {
412
+ return 'unproven';
413
+ }
414
+ let hasMember = false;
415
+ let unresolved = false;
416
+ for (const elem of assign.array.elems) {
417
+ if (elem.index !== undefined || elem.value === undefined)
418
+ return 'unproven';
419
+ const facts = describeWordAtPosition(source, elem.value);
420
+ hasMember ||= facts.fields.min > 0;
421
+ unresolved ||= hasLocaleOrTildeUncertainty(facts.resolution);
422
+ }
423
+ return hasMember ? 'safe' : unresolved ? 'unresolved-word' : 'unproven';
430
424
  }
431
425
  /** Ordinary assignments preserve other names only when no expansion can write indirectly. */
432
426
  function inertAssignment(assign) {
@@ -449,37 +443,61 @@ export function createArraySafetyProof(source) {
449
443
  exits(cmd.y)) {
450
444
  const name = testedArray(cmd.x, true);
451
445
  if (name !== undefined && !variableAttributes) {
452
- return { nounsetOff: facts.nounsetOff, nonEmpty: new Set([...facts.nonEmpty, name]) };
446
+ return {
447
+ nounsetOff: facts.nounsetOff,
448
+ nonEmpty: new Map(facts.nonEmpty).set(name, 'safe'),
449
+ };
453
450
  }
454
451
  }
455
452
  if (cmd?.type !== 'CallExpr') {
456
453
  return UNKNOWN;
457
454
  }
458
455
  if (cmd.args.length === 0 && cmd.assigns.every(inertAssignment)) {
459
- const nonEmpty = new Set(facts.nonEmpty);
456
+ const nonEmpty = new Map(facts.nonEmpty);
460
457
  for (const assign of cmd.assigns) {
461
458
  const name = assign.name?.value;
462
459
  if (name === undefined) {
463
460
  return UNKNOWN;
464
461
  }
465
- nonEmpty.delete(name);
466
- if (literalArray(assign)) {
467
- nonEmpty.add(name);
468
- }
462
+ const evidence = arrayMemberEvidence(assign);
463
+ if (evidence === 'unproven')
464
+ nonEmpty.delete(name);
465
+ else
466
+ nonEmpty.set(name, evidence);
469
467
  }
470
468
  return { nounsetOff: facts.nounsetOff, nonEmpty };
471
469
  }
472
- if (source.getCommandName(cmd) === 'set' && cmd.assigns.length === 0) {
473
- const parsed = parseSetArguments(cmd.args.slice(1).map((arg) => source.resolveWordText(arg)));
474
- if (parsed.stoppedBy === 'unknown' || parsed.stoppedBy === 'malformed') {
470
+ const command = source.getCommandName(cmd);
471
+ if ((command === '[' || command === 'test') &&
472
+ cmd.assigns.length === 0 &&
473
+ cmd.args.every(inert) &&
474
+ inertTest(command, cmd.args.slice(1))) {
475
+ return facts;
476
+ }
477
+ if (command === 'set' && cmd.assigns.length === 0) {
478
+ const args = cmd.args.slice(1);
479
+ const parsed = parseSetWords(source, args);
480
+ if (parsed.stoppedBy === 'malformed')
475
481
  return UNKNOWN;
476
- }
477
482
  let nounsetOff = facts.nounsetOff;
478
483
  for (const change of parsed.changes) {
479
484
  if (change.option === 'nounset') {
480
- nounsetOff = !change.enable;
485
+ nounsetOff = change.enable ? 'unproven' : 'safe';
481
486
  }
482
487
  }
488
+ if (parsed.stoppedBy === 'unknown') {
489
+ const unresolved = args
490
+ .map((arg) => describeWordAtPosition(source, arg).resolution)
491
+ .find((arg) => !arg.static);
492
+ if (unresolved === undefined || !hasLocaleOrTildeUncertainty(unresolved))
493
+ return UNKNOWN;
494
+ // The unresolved word can be the first positional operand. Keep the
495
+ // evidence from the recognized prefix for edit eligibility only.
496
+ return {
497
+ nounsetOff: nounsetOff === 'unproven' ? 'unproven' : 'unresolved-word',
498
+ nonEmpty: new Map([...facts.nonEmpty.keys()].map((name) => [name, 'unresolved-word'])),
499
+ };
500
+ }
483
501
  return { nounsetOff, nonEmpty: facts.nonEmpty };
484
502
  }
485
503
  return UNKNOWN;
@@ -529,7 +547,7 @@ export function createArraySafetyProof(source) {
529
547
  parent.cond.length === 1) {
530
548
  const name = testedArray(parent.cond[0], false);
531
549
  if (name !== undefined) {
532
- facts = { nounsetOff: false, nonEmpty: new Set([name]) };
550
+ facts = { nounsetOff: 'unproven', nonEmpty: new Map([[name, 'safe']]) };
533
551
  }
534
552
  }
535
553
  for (const sibling of siblings(stmt)) {
@@ -540,31 +558,34 @@ export function createArraySafetyProof(source) {
540
558
  }
541
559
  return (node, name) => {
542
560
  if (dynamicEnvironment || variableAttributes) {
543
- return false;
561
+ return 'unproven';
544
562
  }
545
563
  let stmt = source.getParent(node);
546
564
  while (stmt !== undefined && stmt.type !== 'Stmt') {
547
565
  stmt = source.getParent(stmt);
548
566
  }
549
567
  if (stmt?.type !== 'Stmt' || !sequential(stmt)) {
550
- return false;
568
+ return 'unproven';
551
569
  }
552
570
  const cmd = stmt.cmd;
553
571
  if (cmd?.type === 'CallExpr') {
554
572
  if (cmd.assigns.length > 0 || !cmd.args.every(inert)) {
555
- return false;
573
+ return 'unproven';
556
574
  }
557
575
  }
558
576
  else if (cmd?.type === 'ForClause' && cmd.loop?.type === 'WordIter') {
559
577
  if (!cmd.loop.items.every(inert) ||
560
578
  !cmd.loop.items.some((word) => word.range[0] <= node.range[0] && word.range[1] >= node.range[1])) {
561
- return false;
579
+ return 'unproven';
562
580
  }
563
581
  }
564
582
  else {
565
- return false;
583
+ return 'unproven';
566
584
  }
567
585
  const facts = entry(stmt);
568
- return facts.nounsetOff || facts.nonEmpty.has(name);
586
+ const member = facts.nonEmpty.get(name);
587
+ if (facts.nounsetOff === 'safe' || member === 'safe')
588
+ return 'safe';
589
+ return member ?? facts.nounsetOff;
569
590
  };
570
591
  }
@@ -22,6 +22,7 @@
22
22
  * directly. Anything else, including a version captured in another variable,
23
23
  * reports.
24
24
  */
25
+ import { resolveWordTextAtPosition } from '../../language/word-resolution.js';
25
26
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
26
27
  import { resolveTransparentWrappers } from '../resolve-transparent-wrappers.js';
27
28
  import { BUILTIN_WRAPPER } from '../transparent-wrappers.js';
@@ -53,11 +54,11 @@ function shellVersionTest(sourceCode, stmt) {
53
54
  const name = sourceCode.getCommandName(stmt.cmd);
54
55
  if (args.length !== (name === '[' ? 4 : name === 'test' ? 3 : 0))
55
56
  return undefined;
56
- if (name === '[' && sourceCode.resolveWordText(args[3]) !== ']')
57
+ if (name === '[' && resolveWordTextAtPosition(sourceCode, args[3]) !== ']')
57
58
  return undefined;
58
59
  if (!SHELL_VERSION_WORD.test(sourceCode.getText(args[2])))
59
60
  return undefined;
60
- const operator = sourceCode.resolveWordText(args[1]);
61
+ const operator = resolveWordTextAtPosition(sourceCode, args[1]);
61
62
  if (operator === '-n')
62
63
  return 'set';
63
64
  return operator === '-z' ? 'unset' : undefined;
@@ -9,6 +9,7 @@
9
9
  * `-s`), `shopt -o` names `set -o` options, and an operand that is not a
10
10
  * static word cannot be read, so none of those count.
11
11
  */
12
+ import { resolveWordTextAtPosition } from '../../language/word-resolution.js';
12
13
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
13
14
  import { resolveTransparentWrappers } from '../resolve-transparent-wrappers.js';
14
15
  import { BUILTIN_WRAPPER } from '../transparent-wrappers.js';
@@ -43,7 +44,7 @@ export function shoptEnableVisitor(context, option, report) {
43
44
  let namesShellOptions = false;
44
45
  let index = 0;
45
46
  for (; index < words.length; index++) {
46
- const text = sourceCode.resolveWordText(words[index]);
47
+ const text = resolveWordTextAtPosition(sourceCode, words[index]);
47
48
  if (text === null || !/^-./u.test(text))
48
49
  break;
49
50
  if (text === '--') {
@@ -57,7 +58,7 @@ export function shoptEnableVisitor(context, option, report) {
57
58
  if (!enables || disables || namesShellOptions)
58
59
  return;
59
60
  for (const word of words.slice(index)) {
60
- if (sourceCode.resolveWordText(word) === option)
61
+ if (resolveWordTextAtPosition(sourceCode, word) === option)
61
62
  report(word);
62
63
  }
63
64
  },
@@ -18,8 +18,8 @@
18
18
  * `retry curl x` and `retry sudo curl x` are wrapped, while `sudo curl x` and
19
19
  * the `curl` in `retry echo "$(curl x)"` are not.
20
20
  *
21
- * Names are matched by basename when a static command word contains a slash,
22
- * so a path cannot bypass the policy: `/usr/bin/curl x` is `curl`, and
21
+ * A listed command can match by its known basename when the directory varies.
22
+ * For example, `/usr/bin/curl x` is `curl`, and
23
23
  * `/usr/local/bin/retry curl x` is `curl` run through `retry`. This holds for
24
24
  * listed commands, the bound wrapper, and every transparent wrapper followed
25
25
  * (`/usr/bin/sudo curl x` is `curl` run through `sudo`).
@@ -40,10 +40,11 @@
40
40
  * syntax is outside that named-command scope; no-dynamic-invocation reports those
41
41
  * inventory limits when a project requires execution completeness.
42
42
  */
43
+ import { commandBasename } from '../language/command-resolution.js';
43
44
  import { configurationMessage } from '../configuration-message.js';
44
45
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
45
46
  import { resolveTransparentWrappers } from './resolve-transparent-wrappers.js';
46
- import { definedFunctionNames } from '../command-harvest/harvest-commands.js';
47
+ import { definedFunctionNames, mightNamePathFunction, } from '../command-harvest/harvest-commands.js';
47
48
  import { createRule, packageDocsUrl } from './create-rule.js';
48
49
  /**
49
50
  * The messages every wrapper rule reports with. Shared so that a rule which
@@ -228,7 +229,7 @@ function wrapperRuleListeners(compiled, context) {
228
229
  let functions;
229
230
  for (const site of sourceCode.getCommandInventory().commands) {
230
231
  const resolution = resolveChain(compiled, site);
231
- const finding = findListedCommand(compiled, resolution.chain);
232
+ const finding = findListedCommand(compiled, site, resolution);
232
233
  if (finding === null || finding.wrapped)
233
234
  continue;
234
235
  // A function the file defines runs instead of the external command of
@@ -237,7 +238,10 @@ function wrapperRuleListeners(compiled, context) {
237
238
  // external command runs.
238
239
  if (finding.index === 0) {
239
240
  functions ??= definedFunctionNames(sourceCode);
240
- if (functions.has(finding.word))
241
+ const matchesFunction = finding.word === null
242
+ ? mightNamePathFunction(functions, site, resolution.chainIndices[0])
243
+ : functions.has(finding.word);
244
+ if (matchesFunction)
241
245
  continue;
242
246
  }
243
247
  if (isLocalInvocation(compiled, finding, resolution, site))
@@ -326,12 +330,15 @@ function isLocalInvocation(compiled, finding, resolution, site) {
326
330
  * when the next chain word is exactly one of them. The scan stops at the
327
331
  * first word that is not static: `resolveArgv0` never resolves past one.
328
332
  */
329
- function findListedCommand(compiled, chain) {
333
+ function findListedCommand(compiled, site, { chain, chainIndices }) {
330
334
  for (const [index, word] of chain.entries()) {
331
335
  const text = staticText(word);
332
- if (text === null)
333
- return null;
334
- const name = matchName(text, compiled.commands);
336
+ const base = commandBasename(site, word, chainIndices[index]);
337
+ const name = text !== null && compiled.commands.has(text)
338
+ ? text
339
+ : base !== null && compiled.commands.has(base)
340
+ ? base
341
+ : null;
335
342
  if (name === null)
336
343
  continue;
337
344
  let command = name;
@@ -32,6 +32,7 @@
32
32
  * command word. The rule offers no fix and no suggestion; choosing the
33
33
  * command is a human decision.
34
34
  */
35
+ import { functionNames } from '../command-harvest/harvest-commands.js';
35
36
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
36
37
  import { resolveTransparentWrappers } from './resolve-transparent-wrappers.js';
37
38
  import { createRule } from './create-rule.js';
@@ -50,14 +51,12 @@ const NAME_LIST_SCHEMA = {
50
51
  items: { type: 'string', minLength: 1 },
51
52
  uniqueItems: true,
52
53
  };
53
- /**
54
- * Whether `context` places a command inside a function named in `names`, at
55
- * any depth. A function name that is not valid UTF-8 reaches analysis as
56
- * bytes (`Uint8Array`), and a configured name is always a string, so such a
57
- * function never matches.
58
- */
59
- function isInsideFunction(context, names) {
60
- return context.some((frame) => frame.kind === 'function' && typeof frame.name === 'string' && names.has(frame.name));
54
+ /** Whether the command is lexically inside an allowed dispatcher. */
55
+ function isInsideFunction(source, node, names) {
56
+ return source
57
+ .getAncestors(node)
58
+ .some((ancestor) => ancestor.type === 'FuncDecl' &&
59
+ functionNames(source, ancestor).some((name) => names.has(name)));
61
60
  }
62
61
  /**
63
62
  * The `sh/no-dynamic-invocation` rule module.
@@ -107,7 +106,7 @@ export const noDynamicInvocation = createRule({
107
106
  if (effective.reason === 'embedded-command') {
108
107
  context.report({ node: site.node, messageId: 'embeddedCommand' });
109
108
  }
110
- else if (!isInsideFunction(site.context, dispatchers)) {
109
+ else if (!isInsideFunction(sourceCode, site.node, dispatchers)) {
111
110
  context.report({ node: site.node, messageId: 'dynamicInvocation' });
112
111
  }
113
112
  }
@@ -15,9 +15,8 @@
15
15
  * known at run time (`source "$DIR/lib.sh"`, `. $(pick)`) runs code the
16
16
  * reviewer cannot locate. Like `eval`, it is recognized as the effective
17
17
  * command, so `command source "$p"` and `builtin . "$p"` report too; the
18
- * path is the word after the effective command in the call's arguments. A path word is static exactly when
19
- * `ShellSourceCode.resolveWordText` resolves it; this rule never decides
20
- * static-ness itself.
18
+ * path is the word after the effective command in the call's arguments.
19
+ * The language's position-aware resolver determines whether it is static.
21
20
  *
22
21
  * Out of scope, by design: a command word that is itself dynamic
23
22
  * (`$cmd args`) and embedded command strings (`bash -c "$x"`) belong to
@@ -28,6 +27,7 @@
28
27
  * syntax is outside that named-command scope; no-dynamic-invocation reports those
29
28
  * inventory limits when a project requires execution completeness.
30
29
  */
30
+ import { describeWordAtPosition, isSingleField } from '../language/word-resolution.js';
31
31
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
32
32
  import { resolveTransparentWrappers } from './resolve-transparent-wrappers.js';
33
33
  import { createRule } from './create-rule.js';
@@ -82,12 +82,23 @@ export const noEval = createRule({
82
82
  if (!SOURCE_COMMANDS.has(command)) {
83
83
  return;
84
84
  }
85
- // The path is the word right after the effective command, wherever the
86
- // wrapper chain placed that command in the call's arguments.
85
+ // The operand follows the command and an optional end-of-options word.
87
86
  const effectiveIndex = invoked.chainIndices.at(-1);
88
- const path = effectiveIndex === undefined ? undefined : node.args[effectiveIndex + 1];
89
- if (path !== undefined && sourceCode.resolveWordText(path) === null) {
90
- context.report({ node: path, messageId: 'dynamicSource', data: { command } });
87
+ if (effectiveIndex === undefined)
88
+ return;
89
+ let firstOperand = true;
90
+ for (const path of node.args.slice(effectiveIndex + 1)) {
91
+ const facts = describeWordAtPosition(sourceCode, path);
92
+ if (facts.fields.max === 0)
93
+ continue;
94
+ if (firstOperand && facts.resolution.static && facts.resolution.text === '--') {
95
+ firstOperand = false;
96
+ continue;
97
+ }
98
+ if (!facts.resolution.static || !isSingleField(facts)) {
99
+ context.report({ node: path, messageId: 'dynamicSource', data: { command } });
100
+ }
101
+ break;
91
102
  }
92
103
  },
93
104
  };
@@ -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