@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
@@ -1,13 +1,19 @@
1
- import type { ResolveWordOptions, WordResolution } from 'sh-analysis';
1
+ import type { DescribeWordOptions, ResolveWordOptions, WordFacts, WordResolution } from 'sh-analysis';
2
+ import type { ShellDialect } from './shell-language-options.js';
3
+ import type { ShellSourceCode } from './shell-source-code.js';
4
+ import { withoutCrlfCarriageReturn } from './syntax-view.js';
2
5
  import type { ShellNodeOf } from './syntax-view.js';
3
- /**
4
- * Resolves a parsed lint Word using the upstream-shaped syntax associated with it.
5
- * The view supplies locations and selector fields; sh-analysis owns the word
6
- * interpretation. Fabricated or synthetic view nodes have no source syntax and
7
- * are rejected instead of being treated as known or unknown shell values.
8
- * A static word that ends a line of a CRLF file resolves without the line
9
- * terminator's carriage return, as it would on LF input.
10
- * @throws TypeError with `ESLINT_SH_WORD_NODE` for a word without original syntax.
11
- * @internal
12
- */
13
- export declare function resolveWord(word: ShellNodeOf<'Word'>, options?: ResolveWordOptions): WordResolution;
6
+ /** Bats shares Bash expansion rules. @internal */
7
+ export declare function analysisDialect(dialect: ShellDialect): DescribeWordOptions['dialect'];
8
+ /** A word whose expansion occupies exactly one argv position. @internal */
9
+ export declare function isSingleField({ fields }: WordFacts): boolean;
10
+ /** Describes a built-in rule's word at its original AST position. @internal */
11
+ export declare function describeWordAtPosition(source: ShellSourceCode, word: ShellNodeOf<'Word'>): WordFacts;
12
+ /** Quote removal for a function declaration's parser-provided literal name. @internal */
13
+ export declare function resolveFunctionName(source: ShellSourceCode, name: ShellNodeOf<'Lit'>): string | null;
14
+ /** Projects word facts into the same CRLF view as the word resolver. @internal */
15
+ export declare function withLfWordFacts(syntax: Parameters<typeof withoutCrlfCarriageReturn>[0], facts: WordFacts): WordFacts;
16
+ /** The known text of a built-in rule's word at its original AST position. @internal */
17
+ export declare function resolveWordTextAtPosition(source: ShellSourceCode, word: ShellNodeOf<'Word'>): string | null;
18
+ /** Preserves the public helper's context defaults using the source dialect. @internal */
19
+ export declare function resolvePublicWord(source: ShellSourceCode, word: ShellNodeOf<'Word'>, options?: ResolveWordOptions): WordResolution;
@@ -3,8 +3,134 @@
3
3
  * ESLINT_SH_WORD_NODE rejects a missing source association; dynamic words
4
4
  * remain ordinary analysis results rather than errors.
5
5
  */
6
- import { resolveWord as resolveSyntaxWord } from 'sh-analysis';
6
+ import { DashHdoc, Hdoc, WordHdoc } from 'sh-ast';
7
+ import { describeWord, resolveWord as resolveSyntaxWord } from 'sh-analysis';
7
8
  import { syntaxForNode, withoutCrlfCarriageReturn } from './syntax-view.js';
9
+ /** Bats shares Bash expansion rules. @internal */
10
+ export function analysisDialect(dialect) {
11
+ return dialect === 'bats' ? 'bash' : dialect;
12
+ }
13
+ /** A word whose expansion occupies exactly one argv position. @internal */
14
+ export function isSingleField({ fields }) {
15
+ return fields.min === 1 && fields.max === 1;
16
+ }
17
+ const COMMAND_WORD = { context: 'command-argument' };
18
+ const WORD_WITHOUT_FILENAME_GENERATION = {
19
+ context: 'command-argument',
20
+ filenameGeneration: false,
21
+ };
22
+ const ASSIGNMENT_VALUE = {
23
+ context: 'assignment-value',
24
+ filenameGeneration: false,
25
+ };
26
+ /** Options supported by the analyzer for an unquoted position established by the lint tree. */
27
+ function optionsAtPosition(source, word, commandArgumentsOnly = false) {
28
+ const parent = source.getParent(word);
29
+ if (parent?.type === 'CallExpr' && parent.args.includes(word))
30
+ return COMMAND_WORD;
31
+ if (parent?.type === 'Redirect' && (parent.op === Hdoc || parent.op === DashHdoc)) {
32
+ // An isolated word does not establish a heredoc's quoting rules.
33
+ return { filenameGeneration: false, braceExpansion: false };
34
+ }
35
+ if (commandArgumentsOnly)
36
+ return undefined;
37
+ switch (parent?.type) {
38
+ case 'Assign':
39
+ if (parent.value !== word)
40
+ return undefined;
41
+ if (parent.name !== undefined)
42
+ return ASSIGNMENT_VALUE;
43
+ return source.getParent(parent)?.type === 'DeclClause' ? COMMAND_WORD : undefined;
44
+ case 'ArrayElem':
45
+ return parent.value === word && parent.index === undefined ? COMMAND_WORD : undefined;
46
+ case 'BinaryTest':
47
+ case 'UnaryTest':
48
+ case 'TestClause':
49
+ case 'ParenTest':
50
+ case 'CaseClause':
51
+ case 'CaseItem':
52
+ return WORD_WITHOUT_FILENAME_GENERATION;
53
+ case 'WordIter':
54
+ return COMMAND_WORD;
55
+ case 'Redirect':
56
+ // POSIX non-interactive redirections and Bash here-strings suppress filename generation.
57
+ if (parent.word !== word)
58
+ return undefined;
59
+ return source.dialect === 'posix' ||
60
+ (parent.op === WordHdoc && (source.dialect === 'bash' || source.dialect === 'bats'))
61
+ ? WORD_WITHOUT_FILENAME_GENERATION
62
+ : COMMAND_WORD;
63
+ default:
64
+ // In particular, arithmetic subscripts and parameter-expansion operands
65
+ // cannot use a stand-alone unquoted word's escape rules.
66
+ return undefined;
67
+ }
68
+ }
69
+ /** Resolves a built-in rule's word using its original AST position. @internal */
70
+ function resolveWordAtPosition(source, word) {
71
+ return describeWordAtPosition(source, word).resolution;
72
+ }
73
+ /** Describes a built-in rule's word at its original AST position. @internal */
74
+ export function describeWordAtPosition(source, word) {
75
+ const parent = source.getParent(word);
76
+ if (parent?.type === 'CallExpr') {
77
+ const observed = source.getCommandArgumentFacts(parent)?.[parent.args.indexOf(word)];
78
+ if (observed !== undefined)
79
+ return observed;
80
+ }
81
+ const syntax = originalWord(word);
82
+ return withLfWordFacts(syntax, describeWord(syntax, {
83
+ ...optionsAtPosition(source, word),
84
+ dialect: analysisDialect(source.dialect),
85
+ }));
86
+ }
87
+ /** Quote removal for a function declaration's parser-provided literal name. @internal */
88
+ export function resolveFunctionName(source, name) {
89
+ if (source.dialect !== 'zsh')
90
+ return name.value;
91
+ const part = syntaxForNode(name);
92
+ if (part?.Type !== 'Lit')
93
+ return null;
94
+ const result = resolveSyntaxWord({ Type: 'Word', Parts: [part] }, {
95
+ context: 'command-argument',
96
+ dialect: analysisDialect(source.dialect),
97
+ filenameGeneration: false,
98
+ braceExpansion: false,
99
+ });
100
+ return result.static ? result.text : null;
101
+ }
102
+ /** Projects word facts into the same CRLF view as the word resolver. @internal */
103
+ export function withLfWordFacts(syntax, facts) {
104
+ const suffix = withoutCrlfCarriageReturn(syntax, { static: true, text: facts.knownSuffix });
105
+ if (!suffix.static || suffix.text === facts.knownSuffix)
106
+ return facts;
107
+ const basename = facts.basename.known ? facts.basename.text.slice(0, -1) : '';
108
+ const removedOnlyLiteral = suffix.text === '' && !facts.resolution.static;
109
+ return {
110
+ ...facts,
111
+ resolution: withoutCrlfCarriageReturn(syntax, facts.resolution),
112
+ fields: suffix.text === '' && !facts.quoted
113
+ ? { min: 0, max: facts.resolution.static ? 0 : facts.fields.max }
114
+ : removedOnlyLiteral
115
+ ? { ...facts.fields, min: 0 }
116
+ : facts.fields,
117
+ knownPrefix: facts.resolution.static ? suffix.text : facts.knownPrefix,
118
+ knownSuffix: suffix.text,
119
+ basename: basename === '' ? { known: false } : { known: true, text: basename },
120
+ };
121
+ }
122
+ /** The known text of a built-in rule's word at its original AST position. @internal */
123
+ export function resolveWordTextAtPosition(source, word) {
124
+ const result = resolveWordAtPosition(source, word);
125
+ return result.static ? result.text : null;
126
+ }
127
+ /** Preserves the public helper's context defaults using the source dialect. @internal */
128
+ export function resolvePublicWord(source, word, options) {
129
+ return resolveWord(word, {
130
+ ...(options ?? optionsAtPosition(source, word, true)),
131
+ dialect: analysisDialect(source.dialect),
132
+ });
133
+ }
8
134
  /**
9
135
  * Resolves a parsed lint Word using the upstream-shaped syntax associated with it.
10
136
  * The view supplies locations and selector fields; sh-analysis owns the word
@@ -15,10 +141,14 @@ import { syntaxForNode, withoutCrlfCarriageReturn } from './syntax-view.js';
15
141
  * @throws TypeError with `ESLINT_SH_WORD_NODE` for a word without original syntax.
16
142
  * @internal
17
143
  */
18
- export function resolveWord(word, options) {
144
+ function resolveWord(word, options) {
145
+ const syntax = originalWord(word);
146
+ return withoutCrlfCarriageReturn(syntax, resolveSyntaxWord(syntax, options));
147
+ }
148
+ function originalWord(word) {
19
149
  const syntax = syntaxForNode(word);
20
150
  if (syntax?.Type !== 'Word') {
21
151
  throw Object.assign(new TypeError('resolveWord expects a parsed shell Word from this language adapter'), { code: 'ESLINT_SH_WORD_NODE' });
22
152
  }
23
- return withoutCrlfCarriageReturn(syntax, resolveSyntaxWord(syntax, options));
153
+ return syntax;
24
154
  }
@@ -0,0 +1,2 @@
1
+ /** Whether a resolved destination can name a Bash variable or array member. @internal */
2
+ export declare function isBashBuiltinDestination(text: string): boolean;
@@ -0,0 +1,4 @@
1
+ /** Whether a resolved destination can name a Bash variable or array member. @internal */
2
+ export function isBashBuiltinDestination(text) {
3
+ return /^[A-Za-z_][A-Za-z0-9_]*(?:\[[\s\S]+\])?$/u.test(text);
4
+ }
@@ -10,10 +10,10 @@ import type { ShellRuleVisitor } from '../define-shell-rule.js';
10
10
  */
11
11
  export declare const DECLARATION_AND_LOCAL_COMMANDS: ReadonlySet<string>;
12
12
  /**
13
- * Builds the listeners that call `report(optionWord, command, optionWords)` for each
13
+ * Builds the listeners that call `report(node, command, options, text)` for each
14
14
  * `declare` / `typeset` (or each of `commands`) whose option cluster contains
15
15
  * `flag`: one letter, or a character class such as `[lu]` for either of two.
16
16
  *
17
17
  * @internal
18
18
  */
19
- export declare function declarationFlagVisitor(context: TransparentWrappersBindingContext, flag: string, report: (option: ShellNode, command: string, options: readonly string[]) => void, commands?: ReadonlySet<string>): ShellRuleVisitor;
19
+ export declare function declarationFlagVisitor(context: TransparentWrappersBindingContext, flag: string, report: (node: ShellNode, command: string, options: readonly string[], text: string) => void, commands?: ReadonlySet<string>, reportEveryOption?: boolean): ShellRuleVisitor;
@@ -13,6 +13,7 @@
13
13
  * gating an option `local` shares (`-n`, `-l`, `-u`) adds `local` with
14
14
  * {@link DECLARATION_AND_LOCAL_COMMANDS}.
15
15
  */
16
+ import { resolveWordTextAtPosition } from '../../language/word-resolution.js';
16
17
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
17
18
  import { resolveTransparentWrappers } from '../resolve-transparent-wrappers.js';
18
19
  import { BUILTIN_WRAPPER } from '../transparent-wrappers.js';
@@ -40,26 +41,25 @@ const TRANSPARENT_WRAPPERS = [
40
41
  BUILTIN_WRAPPER,
41
42
  ];
42
43
  /**
43
- * Finds the option word carrying `flag` among a declaration command's
44
- * arguments (the words after the command name), together with all of the
45
- * command's option words, or `undefined` when no option word carries it.
44
+ * Finds every word carrying the flag among a declaration command's
45
+ * arguments. Each match shares the list of the command's option words.
46
46
  * Option processing stops at the first operand, at `--`, and at a word that
47
47
  * is not static, because what follows it may not be an option.
48
48
  */
49
- function findFlagOption(sourceCode, flagPattern, args) {
50
- let report;
49
+ function findFlagOptions(sourceCode, flagPattern, args) {
50
+ const matches = [];
51
51
  const options = [];
52
52
  for (const { report: node, word } of args) {
53
53
  if (word === undefined)
54
54
  break;
55
- const text = sourceCode.resolveWordText(word);
55
+ const text = resolveWordTextAtPosition(sourceCode, word);
56
56
  if (text === null || text === '--' || !/^[-+]./u.test(text))
57
57
  break;
58
58
  options.push(text);
59
- if (report === undefined && flagPattern.test(text))
60
- report = node;
59
+ if (flagPattern.test(text))
60
+ matches.push({ report: node, text });
61
61
  }
62
- return report === undefined ? undefined : { report, options };
62
+ return matches.map((match) => ({ ...match, options }));
63
63
  }
64
64
  /**
65
65
  * The arguments of a `DeclClause` as candidates. An option such as `-A` is an
@@ -72,25 +72,33 @@ function declClauseArgs(node) {
72
72
  return { report: word ?? assign, word };
73
73
  });
74
74
  }
75
+ /** Reports the selected matching option words of one command. */
76
+ function optionReporter(sourceCode, flagPattern, report, reportEveryOption) {
77
+ return (command, args) => {
78
+ const matches = findFlagOptions(sourceCode, flagPattern, args);
79
+ for (const option of reportEveryOption ? matches : matches.slice(0, 1)) {
80
+ report(option.report, command, option.options, option.text);
81
+ }
82
+ };
83
+ }
75
84
  /**
76
- * Builds the listeners that call `report(optionWord, command, optionWords)` for each
85
+ * Builds the listeners that call `report(node, command, options, text)` for each
77
86
  * `declare` / `typeset` (or each of `commands`) whose option cluster contains
78
87
  * `flag`: one letter, or a character class such as `[lu]` for either of two.
79
88
  *
80
89
  * @internal
81
90
  */
82
- export function declarationFlagVisitor(context, flag, report, commands = DECLARATION_COMMANDS) {
91
+ export function declarationFlagVisitor(context, flag, report, commands = DECLARATION_COMMANDS, reportEveryOption = false) {
83
92
  const { sourceCode } = context;
84
93
  const transparentWrappers = resolveTransparentWrappers(context, TRANSPARENT_WRAPPERS);
85
94
  const flagPattern = new RegExp(`^-[a-zA-Z]*${flag}[a-zA-Z]*$`, 'u');
95
+ const reportOptions = optionReporter(sourceCode, flagPattern, report, reportEveryOption);
86
96
  return {
87
97
  DeclClause(node) {
88
98
  const command = node.variant?.value;
89
99
  if (command === undefined || !commands.has(command))
90
100
  return;
91
- const option = findFlagOption(sourceCode, flagPattern, declClauseArgs(node));
92
- if (option !== undefined)
93
- report(option.report, command, option.options);
101
+ reportOptions(command, declClauseArgs(node));
94
102
  },
95
103
  CallExpr(node) {
96
104
  const invoked = sourceCode.resolveInvokedCommand(node, {
@@ -105,9 +113,7 @@ export function declarationFlagVisitor(context, flag, report, commands = DECLARA
105
113
  const operands = node.args
106
114
  .slice((invoked.chainIndices.at(-1) ?? 0) + 1)
107
115
  .map((word) => ({ report: word, word }));
108
- const option = findFlagOption(sourceCode, flagPattern, operands);
109
- if (option !== undefined)
110
- report(option.report, command, option.options);
116
+ reportOptions(command, operands);
111
117
  },
112
118
  };
113
119
  }
@@ -41,9 +41,7 @@ export const noCaseAttributes = createCompatRule({
41
41
  },
42
42
  },
43
43
  create(context, gate) {
44
- const { sourceCode } = context;
45
- return declarationFlagVisitor(context, '[lu]', (node, command) => {
46
- const option = (node.type === 'Word' ? sourceCode.resolveWordText(node) : null) ?? '';
44
+ return declarationFlagVisitor(context, '[lu]', (node, command, _options, option) => {
47
45
  if (option.includes('l') && option.includes('u')) {
48
46
  context.report({
49
47
  node,
@@ -58,6 +56,6 @@ export const noCaseAttributes = createCompatRule({
58
56
  messageId: 'caseAttribute',
59
57
  data: { ...gate, command, flag, tr: TR_FOR[flag] },
60
58
  });
61
- }, DECLARATION_AND_LOCAL_COMMANDS);
59
+ }, DECLARATION_AND_LOCAL_COMMANDS, true);
62
60
  },
63
61
  });
@@ -9,24 +9,13 @@
9
9
  * transparent wrappers (`command mapfile …`, `builtin readarray …`), through
10
10
  * `ShellSourceCode.resolveInvokedCommand`.
11
11
  *
12
- * The suggestion rewrites the one shape whose array contents a loop
13
- * reproduces exactly, `mapfile -t [NAME]` written directly (no wrapper, no leading
14
- * `VAR=value` assignment) in a Bash-family file: it becomes a brace group
15
- * that empties the array and appends each line read by
16
- * `while IFS= read -r … || [ -n "$REPLY" ]`. The `|| [ -n "$REPLY" ]` keeps a
17
- * final line that has no trailing newline, as `mapfile -t` does. Reading with
18
- * no variable name keeps every byte of the line, but it assigns `REPLY`:
19
- * unlike `mapfile`, the loop leaves `REPLY` set to the empty string, whatever
20
- * it held (or whether it was set) before. `REPLY` is `read`'s own default
21
- * variable, so this is the narrowest side effect a read loop can have; the
22
- * alternatives (a named loop variable, or saving and restoring `REPLY` in
23
- * another variable) overwrite a name the script is likelier to use. The
24
- * suggestion message states the tradeoff. The brace group keeps the command a single
25
- * unit, so a redirection (`< file`) or pipeline (`cmd | mapfile -t a`) still
26
- * feeds the loop. Other options (`-d`, `-n`, `-O`, `-s`, `-u`, `-C`, or no
27
- * `-t`, which keeps each newline) and POSIX files, which have no arrays at
28
- * all, get the report without a suggestion.
12
+ * The suggestion replaces a direct `mapfile -t` with a read loop when a
13
+ * trailing here-string supplies stdin. Here-strings provide shell text, while
14
+ * files, pipes and inherited stdin may contain NUL bytes that mapfile and read
15
+ * handle differently. The loop intentionally sets `REPLY` to the empty string.
29
16
  */
17
+ import { resolveWordTextAtPosition } from '../../language/word-resolution.js';
18
+ import { WordHdoc } from 'sh-ast';
30
19
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
31
20
  import { resolveTransparentWrappers } from '../resolve-transparent-wrappers.js';
32
21
  import { BUILTIN_WRAPPER } from '../transparent-wrappers.js';
@@ -64,11 +53,19 @@ function rewritableArray(sourceCode, node) {
64
53
  return undefined;
65
54
  if (node.assigns.length > 0)
66
55
  return undefined;
67
- const words = node.args.slice(1).map((word) => sourceCode.resolveWordText(word));
56
+ const stmt = sourceCode.getParent(node);
57
+ if (stmt?.type !== 'Stmt' || stmt.redirs.length !== 1)
58
+ return undefined;
59
+ const [input] = stmt.redirs;
60
+ if (input.op !== WordHdoc ||
61
+ (input.n !== undefined && !/^0+$/u.test(input.n.value)) ||
62
+ input.range[0] < node.range[1])
63
+ return undefined;
64
+ const words = node.args.slice(1).map((word) => resolveWordTextAtPosition(sourceCode, word));
68
65
  if (words.length === 0 || words.length > 2 || words[0] !== '-t')
69
66
  return undefined;
70
67
  const name = words.length === 2 ? words[1] : DEFAULT_ARRAY;
71
- return name !== null && IDENTIFIER.test(name) ? name : undefined;
68
+ return name !== null && name !== 'REPLY' && IDENTIFIER.test(name) ? name : undefined;
72
69
  }
73
70
  /**
74
71
  * The `sh/compat/no-mapfile` rule module.
@@ -1,13 +1,8 @@
1
- /**
2
- * Message ids this rule reports with: `negativeIndex` for the report and
3
- * `useArrayLength` for its suggestion.
4
- *
5
- * @internal
6
- */
7
- export type NoNegativeArrayIndexMessageId = 'negativeIndex' | 'useArrayLength';
1
+ /** Message id for an unsupported negative subscript. @internal */
2
+ export type NoNegativeArrayIndexMessageId = 'negativeIndex';
8
3
  /**
9
4
  * The `sh/compat/no-negative-array-index` rule module.
10
5
  *
11
6
  * @internal
12
7
  */
13
- export declare const noNegativeArrayIndex: import("../define-shell-rule.js").ShellRule<[], NoNegativeArrayIndexMessageId>;
8
+ export declare const noNegativeArrayIndex: import("../define-shell-rule.js").ShellRule<[], "negativeIndex">;
@@ -6,14 +6,8 @@
6
6
  *
7
7
  * Bash 3.2 evaluates `-1` as the arithmetic value minus one and fails with
8
8
  * "bad array subscript", so the read yields nothing and the assignment is
9
- * refused. The message suggests the portable alternative: count from the
10
- * array length, `${arr[$((${#arr[@]}-1))]}`.
11
- *
12
- * The suggestion rewrites exactly a bare `${NAME[-N]}` read to
13
- * `${NAME[$((${#NAME[@]}-N))]}`. Negative subscripts count back from the
14
- * highest assigned index plus one, while `${#NAME[@]}` counts set elements,
15
- * so the two agree only for arrays without holes; the suggestion message says
16
- * so. Assignments and other expansion forms are reported without a suggestion.
9
+ * refused. A length-based index is only equivalent for a dense zero-based
10
+ * array. The rule reports the incompatible syntax without rewriting it.
17
11
  *
18
12
  * What is read: an `Index` that is a unary minus applied to a static
19
13
  * integer (decimal, octal, hexadecimal or base#digits), on a `ParamExp` or an `Assign`.
@@ -27,13 +21,12 @@
27
21
  * `unset` command's operand text, since the parser keeps that operand as an
28
22
  * ordinary word; option words (`-v`) never match an element name.
29
23
  */
24
+ import { resolveWordTextAtPosition } from '../../language/word-resolution.js';
30
25
  import { Minus } from 'sh-ast';
31
26
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
32
27
  import { resolveTransparentWrappers } from '../resolve-transparent-wrappers.js';
33
28
  import { BUILTIN_WRAPPER } from '../transparent-wrappers.js';
34
29
  import { createCompatRule } from './create-compat-rule.js';
35
- /** A bare negative-subscript read, the only shape the suggestion rewrites. */
36
- const BARE_READ = /^\$\{([A-Za-z_][A-Za-z0-9_]*)\[\s*-\s*(\d+)\s*\]\}$/u;
37
30
  /**
38
31
  * The wrappers followed to find an `unset` command: `sh-analysis`'s
39
32
  * defaults (which include `command`) plus Bash's `builtin`.
@@ -80,13 +73,11 @@ export const noNegativeArrayIndex = createCompatRule({
80
73
  feature: 'negativeArrayIndex',
81
74
  meta: {
82
75
  type: 'problem',
83
- hasSuggestions: true,
84
76
  docs: {
85
77
  description: 'Disallow negative array subscripts (`${arr[-1]}`) when the target shell lacks them',
86
78
  },
87
79
  messages: {
88
- negativeIndex: 'Negative array subscripts need {{required}}, but this file must support {{target}}. Count from the length instead, for example `${arr[$((${#arr[@]}-1))]}`.',
89
- useArrayLength: 'Replace with `${{{name}}[$((${#{{name}}[@]}-{{n}}))]}` (the two differ only for an array with unset elements).',
80
+ negativeIndex: 'Negative array subscripts need {{required}}, but this file must support {{target}}. Use a nonnegative index. A length-based index is equivalent only for a dense zero-based array.',
90
81
  },
91
82
  },
92
83
  create(context, gate) {
@@ -101,7 +92,7 @@ export const noNegativeArrayIndex = createCompatRule({
101
92
  // only a Word can be resolved, and `-0` is zero, not a negative index.
102
93
  if (operand?.type !== 'Word')
103
94
  return false;
104
- const digits = sourceCode.resolveWordText(operand) ?? '';
95
+ const digits = resolveWordTextAtPosition(sourceCode, operand) ?? '';
105
96
  return isNonzeroInteger(digits);
106
97
  }
107
98
  return {
@@ -115,7 +106,7 @@ export const noNegativeArrayIndex = createCompatRule({
115
106
  for (const word of node.args.slice((invoked.chainIndices.at(-1) ?? 0) + 1)) {
116
107
  // An unquoted `a[-1]` holds a glob bracket, so it is not "static"; its
117
108
  // written text is what names the element.
118
- const text = sourceCode.resolveWordText(word) ?? sourceCode.getText(word);
109
+ const text = resolveWordTextAtPosition(sourceCode, word) ?? sourceCode.getText(word);
119
110
  if (text === '--')
120
111
  continue;
121
112
  const match = UNSET_NEGATIVE.exec(text);
@@ -127,21 +118,7 @@ export const noNegativeArrayIndex = createCompatRule({
127
118
  ParamExp(node) {
128
119
  if (!isNegativeLiteral(node.index))
129
120
  return;
130
- const match = BARE_READ.exec(sourceCode.getText(node));
131
- context.report({
132
- node,
133
- messageId: 'negativeIndex',
134
- data: { ...gate },
135
- suggest: match === null
136
- ? []
137
- : [
138
- {
139
- messageId: 'useArrayLength',
140
- data: { name: match[1], n: match[2] },
141
- fix: (fixer) => fixer.replaceText(node, `\${${match[1]}[$((\${#${match[1]}[@]}-${match[2]}))]}`),
142
- },
143
- ],
144
- });
121
+ context.report({ node, messageId: 'negativeIndex', data: { ...gate } });
145
122
  },
146
123
  Assign(node) {
147
124
  if (!isNegativeLiteral(node.index))
@@ -42,10 +42,12 @@
42
42
  * `nounset-array-proof.ts` owns those boundaries. Reports remain conditional:
43
43
  * unknown state is a reason to report, not proof that the array is empty.
44
44
  */
45
+ import { parseSetWords } from '../strict-mode-prologue.js';
46
+ import { resolveWordTextAtPosition } from '../../language/word-resolution.js';
45
47
  import { AlternateUnset, AlternateUnsetOrNull } from 'sh-ast';
46
48
  import { createCompatRule } from './create-compat-rule.js';
47
49
  import { createArraySafetyProof } from './nounset-array-proof.js';
48
- import { parseSetArguments, shebangOptionChanges } from '../set-options.js';
50
+ import { shebangOptionChanges } from '../set-options.js';
49
51
  /** A shell variable name. */
50
52
  const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/u;
51
53
  /**
@@ -88,7 +90,7 @@ export const noNounsetEmptyArray = createCompatRule({
88
90
  function wholeArraySubscript(index) {
89
91
  if (index?.type !== 'Word')
90
92
  return undefined;
91
- const text = sourceCode.resolveWordText(index) ?? sourceCode.getText(index);
93
+ const text = resolveWordTextAtPosition(sourceCode, index) ?? sourceCode.getText(index);
92
94
  return text === '@' || text === '*' ? text : undefined;
93
95
  }
94
96
  /**
@@ -121,8 +123,8 @@ export const noNounsetEmptyArray = createCompatRule({
121
123
  CallExpr(node) {
122
124
  if (sourceCode.getCommandName(node) !== 'set')
123
125
  return;
124
- const args = node.args.slice(1).map((word) => sourceCode.resolveWordText(word));
125
- if (enablesNounset(parseSetArguments(args).changes))
126
+ const args = node.args.slice(1);
127
+ if (enablesNounset(parseSetWords(sourceCode, args).changes))
126
128
  nounset = true;
127
129
  },
128
130
  ParamExp(node) {
@@ -142,9 +144,10 @@ export const noNounsetEmptyArray = createCompatRule({
142
144
  'File:exit'() {
143
145
  if (!nounset || candidates.length === 0)
144
146
  return;
145
- const provenSafe = createArraySafetyProof(sourceCode);
147
+ const arraySafety = createArraySafetyProof(sourceCode);
146
148
  for (const { node, name, subscript } of candidates) {
147
- if (provenSafe(node, name))
149
+ const safety = arraySafety(node, name);
150
+ if (safety === 'safe')
148
151
  continue;
149
152
  const replacement = guardedExpansion(name, subscript);
150
153
  const quoted = wholeQuotedWord(node);
@@ -152,7 +155,7 @@ export const noNounsetEmptyArray = createCompatRule({
152
155
  node,
153
156
  messageId: 'emptyArray',
154
157
  data: { ...gate, name, subscript, example: replacement },
155
- suggest: quoted === undefined
158
+ suggest: quoted === undefined || safety === 'unresolved-word'
156
159
  ? []
157
160
  : [
158
161
  {
@@ -19,6 +19,7 @@
19
19
  * What is read: a `ParamExp` whose expansion operator is `@` followed by one
20
20
  * of the letters above. The report is on the whole expansion.
21
21
  */
22
+ import { resolveWordTextAtPosition } from '../../language/word-resolution.js';
22
23
  import { OtherParamOps } from 'sh-ast';
23
24
  import { createMultiFeatureCompatRule } from './create-compat-rule.js';
24
25
  import { TO_LOWER, TO_UPPER, trExample } from './no-case-modification.js';
@@ -96,7 +97,7 @@ export const noParameterTransformation = createMultiFeatureCompatRule({
96
97
  const { exp } = node;
97
98
  if (exp?.op !== OtherParamOps || exp.word === undefined)
98
99
  return;
99
- const operator = sourceCode.resolveWordText(exp.word);
100
+ const operator = resolveWordTextAtPosition(sourceCode, exp.word);
100
101
  if (operator === null)
101
102
  return;
102
103
  const feature = OPERATOR_FEATURES.get(operator);
@@ -7,17 +7,16 @@
7
7
  * nothing is printed. The message suggests the portable alternative for the
8
8
  * current time: `date '+fmt'`, which takes the same `strftime` format.
9
9
  *
10
- * What is read: a `printf` command (after transparent wrappers such as
11
- * `builtin`) whose format argument, after an optional `-v name` and `--`, is
12
- * a static word containing a `%(…)T` directive. The format is scanned as
13
- * `printf` reads it: `%%` is a literal percent sign, and a directive may
14
- * carry flags, a width and a precision before the `(`. A format that is not
15
- * static cannot be read, and is not reported. The report is on the format
16
- * word.
10
+ * The rule reads the first format field of a `printf` invocation, after
11
+ * optional `-v name` and `--` operands. It scans exact text and known
12
+ * literal edges for directives, honoring `%%`, flags, width and precision.
13
+ * The report points to the format word.
17
14
  */
15
+ import { describeWordAtPosition, isSingleField } from '../../language/word-resolution.js';
18
16
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
19
17
  import { resolveTransparentWrappers } from '../resolve-transparent-wrappers.js';
20
18
  import { BUILTIN_WRAPPER } from '../transparent-wrappers.js';
19
+ import { isBashBuiltinDestination } from './bash-builtin-destination.js';
21
20
  import { createCompatRule } from './create-compat-rule.js';
22
21
  /**
23
22
  * The wrappers followed to find the `printf` command: `sh-analysis`'s
@@ -80,21 +79,44 @@ export const noPrintfTimeFormat = createCompatRule({
80
79
  if (invoked?.effective.static !== true || invoked.effective.text !== 'printf')
81
80
  return;
82
81
  // `chainIndices` index `node.args` directly, so slice before filtering.
83
- const words = node.args.slice((invoked.chainIndices.at(-1) ?? 0) + 1);
82
+ const words = node.args
83
+ .slice((invoked.chainIndices.at(-1) ?? 0) + 1)
84
+ .map((word) => ({ word, facts: describeWordAtPosition(sourceCode, word) }))
85
+ .filter(({ facts }) => facts.fields.max !== 0);
84
86
  let index = 0;
85
- const first = words.at(0);
86
- if (first !== undefined && sourceCode.resolveWordText(first) === '-v')
87
+ const first = words.at(0)?.facts.resolution;
88
+ if (first?.static && first.text === '-v') {
89
+ const destination = words.at(1)?.facts;
90
+ if (destination === undefined || !isSingleField(destination))
91
+ return;
92
+ if (destination.resolution.static &&
93
+ !isBashBuiltinDestination(destination.resolution.text))
94
+ return;
87
95
  index = 2;
88
- if (index < words.length && sourceCode.resolveWordText(words[index]) === '--')
96
+ }
97
+ else if (first?.static && first.text.startsWith('-v')) {
98
+ if (!isBashBuiltinDestination(first.text.slice(2)))
99
+ return;
100
+ index = 1;
101
+ }
102
+ const option = words.at(index)?.facts.resolution;
103
+ if (option?.static && option.text === '--')
89
104
  index++;
90
- const formatWord = words.at(index);
91
- if (formatWord === undefined)
105
+ const entry = words.at(index);
106
+ if (entry === undefined || !isSingleField(entry.facts))
92
107
  return;
93
- const text = sourceCode.resolveWordText(formatWord);
94
- const format = text === null ? undefined : timeFormatIn(text);
108
+ const { word, facts } = entry;
109
+ const text = facts.resolution.static ? facts.resolution.text : facts.knownPrefix;
110
+ let format = timeFormatIn(text);
111
+ if (format === undefined &&
112
+ facts.features.every((feature) => feature === 'locale' || feature === 'tilde')) {
113
+ // The exact format can depend on encoding or a tilde directory.
114
+ // Recognize the directive in the literal suffix of that format.
115
+ format = timeFormatIn(facts.knownSuffix);
116
+ }
95
117
  if (format === undefined)
96
118
  return;
97
- context.report({ node: formatWord, messageId: 'printfTime', data: { ...gate, format } });
119
+ context.report({ node: word, messageId: 'printfTime', data: { ...gate, format } });
98
120
  },
99
121
  };
100
122
  },