@eslint-sh/eslint-plugin 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +5 -2
  2. package/dist/api.d.ts +1 -1
  3. package/dist/command-harvest/harvest-commands.d.ts +10 -4
  4. package/dist/command-harvest/harvest-commands.js +39 -10
  5. package/dist/eslint-plugin-api.d.ts +36 -14
  6. package/dist/language/command-resolution.d.ts +16 -6
  7. package/dist/language/command-resolution.js +44 -17
  8. package/dist/language/line-breaks.d.ts +10 -4
  9. package/dist/language/line-breaks.js +14 -5
  10. package/dist/language/shell-language.d.ts +2 -0
  11. package/dist/language/shell-language.js +10 -1
  12. package/dist/language/shell-source-code.d.ts +29 -13
  13. package/dist/language/shell-source-code.js +126 -55
  14. package/dist/language/word-resolution.d.ts +18 -12
  15. package/dist/language/word-resolution.js +133 -3
  16. package/dist/rules/compat/bash-builtin-destination.d.ts +2 -0
  17. package/dist/rules/compat/bash-builtin-destination.js +4 -0
  18. package/dist/rules/compat/declaration-options.d.ts +2 -2
  19. package/dist/rules/compat/declaration-options.js +23 -17
  20. package/dist/rules/compat/no-case-attributes.js +2 -4
  21. package/dist/rules/compat/no-mapfile.js +16 -19
  22. package/dist/rules/compat/no-negative-array-index.d.ts +3 -8
  23. package/dist/rules/compat/no-negative-array-index.js +7 -30
  24. package/dist/rules/compat/no-nounset-empty-array.js +10 -7
  25. package/dist/rules/compat/no-parameter-transformation.js +2 -1
  26. package/dist/rules/compat/no-printf-time-format.js +38 -16
  27. package/dist/rules/compat/no-source.d.ts +3 -8
  28. package/dist/rules/compat/no-source.js +3 -40
  29. package/dist/rules/compat/no-test-v.js +243 -61
  30. package/dist/rules/compat/no-wait-n.js +43 -12
  31. package/dist/rules/compat/nounset-array-proof.d.ts +3 -1
  32. package/dist/rules/compat/nounset-array-proof.js +84 -63
  33. package/dist/rules/compat/posix-absent-command.js +3 -2
  34. package/dist/rules/compat/shopt-options.js +3 -2
  35. package/dist/rules/create-wrapper-rule.js +16 -9
  36. package/dist/rules/no-dynamic-invocation.js +8 -9
  37. package/dist/rules/no-eval.js +19 -8
  38. package/dist/rules/no-masked-exit-status.js +34 -46
  39. package/dist/rules/no-secret-flags.js +4 -3
  40. package/dist/rules/no-unchecked-cd.d.ts +8 -3
  41. package/dist/rules/no-unchecked-cd.js +54 -25
  42. package/dist/rules/no-unused-declarations.js +127 -30
  43. package/dist/rules/prefer-local.js +146 -52
  44. package/dist/rules/require-shebang.js +23 -21
  45. package/dist/rules/require-strict-mode.d.ts +2 -2
  46. package/dist/rules/require-strict-mode.js +28 -16
  47. package/dist/rules/require-tty-guard.d.ts +2 -0
  48. package/dist/rules/require-tty-guard.js +205 -50
  49. package/dist/rules/set-options.d.ts +5 -16
  50. package/dist/rules/set-options.js +17 -45
  51. package/dist/rules/shebang-interpreter.d.ts +33 -10
  52. package/dist/rules/shebang-interpreter.js +522 -53
  53. package/dist/rules/shebang-matches-dialect.js +4 -4
  54. package/dist/rules/strict-mode-prologue.d.ts +9 -2
  55. package/dist/rules/strict-mode-prologue.js +45 -8
  56. package/dist/rules/variable-reads.d.ts +12 -0
  57. package/dist/rules/variable-reads.js +31 -0
  58. package/docs/custom-rule-tutorial.md +19 -10
  59. package/docs/error-codes.md +6 -1
  60. package/docs/examples/no-curl-in-functions-rule.mjs +7 -5
  61. package/docs/rules/README.md +5 -5
  62. package/docs/rules/compat/no-mapfile.md +11 -20
  63. package/docs/rules/compat/no-negative-array-index.md +9 -22
  64. package/docs/rules/compat/no-nounset-empty-array.md +5 -5
  65. package/docs/rules/compat/no-printf-time-format.md +2 -1
  66. package/docs/rules/compat/no-source.md +8 -17
  67. package/docs/rules/compat/no-test-v.md +7 -1
  68. package/docs/rules/compat/no-wait-n.md +3 -1
  69. package/docs/rules/no-dynamic-invocation.md +3 -0
  70. package/docs/rules/no-eval.md +22 -1
  71. package/docs/rules/no-masked-exit-status.md +4 -1
  72. package/docs/rules/no-secret-flags.md +22 -2
  73. package/docs/rules/no-unchecked-cd.md +2 -1
  74. package/docs/rules/no-undeclared-commands.md +1 -1
  75. package/docs/rules/no-unused-declarations.md +18 -9
  76. package/docs/rules/prefer-local.md +15 -33
  77. package/docs/rules/require-network-wrapper.md +1 -1
  78. package/docs/rules/require-shebang.md +46 -3
  79. package/docs/rules/require-strict-mode.md +40 -15
  80. package/docs/rules/require-tty-guard.md +27 -4
  81. package/docs/rules/shebang-matches-dialect.md +3 -0
  82. package/docs/shellcheck.md +1 -1
  83. package/docs/wrapper-rules.md +1 -1
  84. package/package.json +4 -4
package/README.md CHANGED
@@ -102,7 +102,7 @@ ShellLanguage }, rules, configs: { recommended, 'agent-authored', 'bash-3.2', 'p
102
102
  gets the same answer: `resolveWord(word, options?)` (the full `WordResolution`) and
103
103
  `resolveWordText(word, options?)` (exactly its static text, or `null`). Both use grammar-position
104
104
  defaults: command-argument context for `CallExpr.args`, conservative tilde handling elsewhere;
105
- explicit options override those defaults. Helpers also include `getCommandName(callExpr)` (the static command word,
105
+ explicit options override those context defaults. Word and command analysis use the parsed dialect. Helpers also include `getCommandName(callExpr)` (the static command word,
106
106
  without following wrappers), and `resolveInvokedCommand(callExpr, { transparentWrappers? })` (the
107
107
  full `Argv0Resolution` once wrappers such as `env`, `sudo`, and `exec` are followed, including the
108
108
  wrapper `chain` and the `effective` command or the reason it is unknowable). The `dialect` and
@@ -133,6 +133,9 @@ ShellLanguage }, rules, configs: { recommended, 'agent-authored', 'bash-3.2', 'p
133
133
  which follows wrappers. `ResolveArgv0Options` is that method's option bag (and
134
134
  `ShellSourceCode.resolveInvokedCommand`'s): `transparentWrappers` replaces the wrapper table
135
135
  followed.
136
+ - `WordFacts` — facts for each word in a site's `argvFacts` array, in the same order as `argv`.
137
+ Each entry includes the resolution, field-count bounds, expansion features, known prefix and
138
+ suffix, known basename, and whether the word is quoted or escaped.
136
139
  - `WordResolution` — what `ShellSourceCode.resolveWord` and a site's `argv` words report: `{ static: true, text }`
137
140
  when the word's value is known without running the script, or `{ static: false, reason }` when
138
141
  it is not (`reason` is `'expansion'`, `'tilde'`, `'glob'`, `'brace'`, `'locale'` or
@@ -198,7 +201,7 @@ import { parseSync, printSync, walk } from 'sh-ast';
198
201
  import { DEFAULT_TRANSPARENT_WRAPPERS, enumerateCommands } from 'sh-analysis';
199
202
  ```
200
203
 
201
- The supported dependency ranges are `sh-ast@^0.11.0` and `sh-analysis@^0.1.0`.
204
+ The supported dependency ranges are `sh-ast@^0.13.0` and `sh-analysis@^0.4.0`.
202
205
  The plugin has no syntax forwarding subpaths. Raw `resolveWord` from `sh-analysis` accepts
203
206
  faithful syntax records; `context.sourceCode.resolveWord` maps an ESLint Word view to its
204
207
  original syntax and applies grammar-position defaults.
package/dist/api.d.ts CHANGED
@@ -9,7 +9,7 @@ export type { ShellLanguage } from './language/shell-language.js';
9
9
  export type { ShellSourceCode } from './language/shell-source-code.js';
10
10
  export type { NormalizedShellLanguageOptions, ShellLanguageOptions, ShellLanguageOptionsJSON, } from './language/shell-language-options.js';
11
11
  export type { Argv0Resolution } from 'sh-analysis';
12
- export type { CommandContext, ResolveArgv0Options, WordResolution } from 'sh-analysis';
12
+ export type { CommandContext, ResolveArgv0Options, WordFacts, WordResolution } from 'sh-analysis';
13
13
  export type { ShellCommandSite, ShellCommandInventory, ShellCommandUncertainty, } from './language/command-resolution.js';
14
14
  export type { ShellComment, ShellFile, ShellNode, ShellNodeField, ShellNodeMap, ShellNodeOf, ShellNodeType, ShellPosition, } from './language/syntax-view.js';
15
15
  export type { ShellDialect } from './language/shell-language-options.js';
@@ -1,7 +1,7 @@
1
1
  import type { WrapperSpec } from 'sh-analysis';
2
2
  import type { ShellCommandSite, ShellCommandUncertainty } from '../language/command-resolution.js';
3
3
  import type { ShellSourceCode } from '../language/shell-source-code.js';
4
- import type { ShellNode } from '../language/syntax-view.js';
4
+ import type { ShellNode, ShellNodeOf } from '../language/syntax-view.js';
5
5
  /**
6
6
  * Options for {@link harvestCommands}.
7
7
  *
@@ -15,6 +15,8 @@ export interface HarvestCommandsOptions {
15
15
  * Defaults to `DEFAULT_TRANSPARENT_WRAPPERS`.
16
16
  */
17
17
  readonly transparentWrappers?: readonly WrapperSpec[];
18
+ /** Whether an invocation of a name defined in the file can be excluded. */
19
+ readonly excludeFunction?: (name: string, site: ShellCommandSite) => boolean;
18
20
  }
19
21
  /**
20
22
  * The first use of one external command in a file.
@@ -45,6 +47,8 @@ export interface CommandHarvest {
45
47
  /** Opaque syntax whose dependencies remain unknown. */
46
48
  readonly uncertainties: readonly ShellCommandUncertainty[];
47
49
  }
50
+ /** The names introduced by one declaration, including zsh's multi-name form. @internal */
51
+ export declare function functionNames(source: ShellSourceCode, node: ShellNodeOf<'FuncDecl'>): readonly string[];
48
52
  /**
49
53
  * The names of every function the file defines, anywhere in it (top level,
50
54
  * nested in another function, inside a conditional, …). Position is not read,
@@ -56,16 +60,18 @@ export interface CommandHarvest {
56
60
  * @internal
57
61
  */
58
62
  export declare function definedFunctionNames(sourceCode: ShellSourceCode): ReadonlySet<string>;
63
+ /** A variable directory can still select a function with the complete path as its name. @internal */
64
+ export declare function mightNamePathFunction(names: ReadonlySet<string>, site: ShellCommandSite, index: number): boolean;
59
65
  /**
60
66
  * Returns known represented external commands `sourceCode` runs, keyed by name, each with
61
67
  * its first use. The map iterates in first-use (source) order.
62
68
  *
63
- * A command is every static word in an invocation's wrapper chain (the
69
+ * A command is every known name or basename in an invocation's wrapper chain (the
64
70
  * wrappers and the effective command), excluding:
65
71
  *
66
- * - dynamic words, which name no knowable command;
72
+ * - words with neither known text nor a known basename;
67
73
  * - builtins of the file's dialect (`sourceCode.dialect`);
68
- * - functions the file defines anywhere.
74
+ * - functions the file defines anywhere, subject to `options.excludeFunction`.
69
75
  *
70
76
  * @throws `ShAnalyzeMaxDepthError` (`SH_ANALYSIS_MAX_DEPTH`, from `sh-analysis`) when the file's
71
77
  * nesting exceeds analysis's recursion guard: a partial harvest would miss
@@ -27,9 +27,19 @@
27
27
  * first-use report nodes. Opaque analysis boundaries travel with the harvest;
28
28
  * known observations do not prove exhaustive dependencies.
29
29
  */
30
+ import { resolveFunctionName } from '../language/word-resolution.js';
31
+ import { commandBasename } from '../language/command-resolution.js';
30
32
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
31
33
  import { walkShell } from '../language/syntax-view.js';
32
34
  import { builtinsForDialect } from './builtins/index.js';
35
+ /** The names introduced by one declaration, including zsh's multi-name form. @internal */
36
+ export function functionNames(source, node) {
37
+ const names = node.name === undefined ? node.names : [node.name];
38
+ return names.flatMap((lit) => {
39
+ const name = resolveFunctionName(source, lit);
40
+ return name === null ? [] : [name];
41
+ });
42
+ }
33
43
  /**
34
44
  * The names of every function the file defines, anywhere in it (top level,
35
45
  * nested in another function, inside a conditional, …). Position is not read,
@@ -45,13 +55,25 @@ export function definedFunctionNames(sourceCode) {
45
55
  walkShell(sourceCode.ast, (node) => {
46
56
  if (node.type !== 'FuncDecl')
47
57
  return;
48
- if (node.name)
49
- names.add(node.name.value);
50
- for (const lit of node.names)
51
- names.add(lit.value);
58
+ for (const name of functionNames(sourceCode, node))
59
+ names.add(name);
52
60
  });
53
61
  return names;
54
62
  }
63
+ /** A variable directory can still select a function with the complete path as its name. @internal */
64
+ export function mightNamePathFunction(names, site, index) {
65
+ const facts = site.argvFacts.at(index);
66
+ if (facts === undefined || !facts.basename.known || facts.resolution.static)
67
+ return false;
68
+ const { knownPrefix, knownSuffix } = facts;
69
+ for (const name of names) {
70
+ if (name.length >= knownPrefix.length + knownSuffix.length &&
71
+ name.startsWith(knownPrefix) &&
72
+ name.endsWith(knownSuffix))
73
+ return true;
74
+ }
75
+ return false;
76
+ }
55
77
  /**
56
78
  * The `Word` node in `site`'s command at argv position `index`. argv and the
57
79
  * `CallExpr`'s `args` list the same words in the same order, so a position
@@ -64,12 +86,12 @@ function wordNodeAt(site, index) {
64
86
  * Returns known represented external commands `sourceCode` runs, keyed by name, each with
65
87
  * its first use. The map iterates in first-use (source) order.
66
88
  *
67
- * A command is every static word in an invocation's wrapper chain (the
89
+ * A command is every known name or basename in an invocation's wrapper chain (the
68
90
  * wrappers and the effective command), excluding:
69
91
  *
70
- * - dynamic words, which name no knowable command;
92
+ * - words with neither known text nor a known basename;
71
93
  * - builtins of the file's dialect (`sourceCode.dialect`);
72
- * - functions the file defines anywhere.
94
+ * - functions the file defines anywhere, subject to `options.excludeFunction`.
73
95
  *
74
96
  * @throws `ShAnalyzeMaxDepthError` (`SH_ANALYSIS_MAX_DEPTH`, from `sh-analysis`) when the file's
75
97
  * nesting exceeds analysis's recursion guard: a partial harvest would miss
@@ -86,11 +108,18 @@ export function harvestCommands(sourceCode, options = {}) {
86
108
  for (const site of sourceCode.getCommandInventory().commands) {
87
109
  const { chain, chainIndices } = site.resolveInvokedCommand({ transparentWrappers });
88
110
  for (const [position, word] of chain.entries()) {
89
- if (!word.static)
111
+ const name = word.static ? word.text : commandBasename(site, word, chainIndices[position]);
112
+ if (name === null || harvested.has(name))
113
+ continue;
114
+ if (word.static && builtins.has(name))
115
+ continue;
116
+ if (position === 0 &&
117
+ options.excludeFunction === undefined &&
118
+ mightNamePathFunction(functions, site, chainIndices[position]))
90
119
  continue;
91
- const name = word.text;
92
- if (harvested.has(name) || builtins.has(name) || functions.has(name))
120
+ if (word.static && functions.has(name) && (options.excludeFunction?.(name, site) ?? true)) {
93
121
  continue;
122
+ }
94
123
  harvested.set(name, { name, node: wordNodeAt(site, chainIndices[position]), site });
95
124
  }
96
125
  }
@@ -27,6 +27,7 @@ import type { SourceLocation } from '@eslint/core';
27
27
  import type { SyntaxPos } from 'sh-ast';
28
28
  import { TextSourceCodeBase } from '@eslint/plugin-kit';
29
29
  import type { TraversalStep } from '@eslint/core';
30
+ import { WordFacts } from 'sh-analysis';
30
31
  import { WordResolution } from 'sh-analysis';
31
32
  import { WrapperSpec } from 'sh-analysis';
32
33
 
@@ -520,7 +521,8 @@ export declare interface ShellCommandSite {
520
521
  * The path from the file root to this command, outermost frame first,
521
522
  * exactly as `sh-analysis` reports it. For example, `date` in
522
523
  * `f() { echo "$(date)"; }` has
523
- * `[{ kind: 'function', name: 'f' }, { kind: 'cmdSubst' }]`.
524
+ * `[{ kind: 'function', names: ['f'] }, { kind: 'cmdSubst' }]`.
525
+ * Function frames list names in declaration order. Anonymous functions have an empty list.
524
526
  */
525
527
  readonly context: readonly CommandContext[];
526
528
  /** The command word (`argv[0]`) resolved with `{ context: 'command-argument' }`. */
@@ -531,6 +533,8 @@ export declare interface ShellCommandSite {
531
533
  * assignments are not part of argv.
532
534
  */
533
535
  readonly argv: readonly WordResolution[];
536
+ /** Word facts for the same original argv positions, using the parsed dialect. */
537
+ readonly argvFacts: readonly WordFacts[];
534
538
  /**
535
539
  * Follows this command's argv0 through transparent wrappers (`env`, `sudo`,
536
540
  * `nohup`, `exec`, …) and returns `sh-analysis`'s `resolveArgv0`
@@ -538,7 +542,7 @@ export declare interface ShellCommandSite {
538
542
  * `ShellSourceCode.resolveInvokedCommand(node, options)`; both read the
539
543
  * same per-file index.
540
544
  *
541
- * @param options - Forwarded to `resolveArgv0` unchanged.
545
+ * @param options - Wrapper and interpreter settings. Resolution uses the parsed dialect.
542
546
  * `transparentWrappers` replaces `sh-analysis`'s
543
547
  * `DEFAULT_TRANSPARENT_WRAPPERS`; spread the defaults into the array to
544
548
  * extend them instead.
@@ -1047,10 +1051,15 @@ export declare interface ShellRuleVisitor extends ShellTypedListeners {
1047
1051
  * `sh-analysis` owns static-word interpretation and dynamic reasons; this
1048
1052
  * method supplies the lint tree's position-based policy, without executing shell.
1049
1053
  *
1050
- * Without explicit options, `CallExpr.args` use command-argument context, so
1051
- * `PATH=a:~/bin` is literal there. Other positions retain the analyzer's
1052
- * conservative default, including tilde expansion after an unquoted colon.
1053
- * Explicit options are forwarded unchanged, even when empty.
1054
+ * Without explicit options, `CallExpr.args` use command-argument context.
1055
+ * An ordinary argument such as `a:~/bin` is literal in that context, while
1056
+ * `PATH=a:~/bin` is dynamic because Bash can expand the tilde in an
1057
+ * assignment-shaped argument. Other positions use the analyzer's
1058
+ * conservative default, which also considers assignment-value expansion.
1059
+ * Explicit options override the context defaults. Resolution uses the parsed dialect.
1060
+ * Since sh-analysis 0.3, a top-level escaped literal can return `unsupported`
1061
+ * when the analyzer receives no context. For the assignment value in
1062
+ * `label=a\ b`, pass `{ context: 'assignment-value' }` to resolve `a b`.
1054
1063
  *
1055
1064
  * @param word - A parsed Word from the lint view.
1056
1065
  * @param options - Explicit analysis policy overriding grammar defaults.
@@ -1099,10 +1108,11 @@ export declare interface ShellRuleVisitor extends ShellTypedListeners {
1099
1108
  * assignment-only statement such as `FOO=1`).
1100
1109
  *
1101
1110
  * Delegates to `resolveArgv0` with the `CommandSite` that `enumerateCommands`
1102
- * reports for this `CallExpr` in this file, so it inherits that function's
1103
- * guarantee that an unknowable word is never guessed through. Read the
1104
- * effective command's name as
1105
- * `res.effective.static ? res.effective.text : null`.
1111
+ * reports for this `CallExpr` in this file. A wrapper that accepts assignments
1112
+ * can skip a fixed scalar assignment prefix when the operand is known to
1113
+ * occupy one field, even if the value is dynamic. For example,
1114
+ * `env PATH=a:~/bin printf hi` resolves to `printf`. Read the effective
1115
+ * command's name as `res.effective.static ? res.effective.text : null`.
1106
1116
  * `sudo -u x "$prog"` and `exec "$@"` have a non-static `effective` with
1107
1117
  * reason `expansion`; `env -S '…'` and `bash -c '…'` have reason
1108
1118
  * `embedded-command`; `chain`
@@ -1125,7 +1135,7 @@ export declare interface ShellRuleVisitor extends ShellTypedListeners {
1125
1135
  * index would silently omit real commands.
1126
1136
  *
1127
1137
  * @param callExpr - A parsed `CallExpr` node from this file's lint tree.
1128
- * @param options - Forwarded to `resolveArgv0` unchanged.
1138
+ * @param options - Wrapper and interpreter settings. Resolution uses the parsed dialect.
1129
1139
  * `transparentWrappers` replaces `sh-analysis`'s
1130
1140
  * `DEFAULT_TRANSPARENT_WRAPPERS`; spread the defaults into the array to
1131
1141
  * extend them instead.
@@ -1235,6 +1245,11 @@ export declare interface ShellRuleVisitor extends ShellTypedListeners {
1235
1245
  * The range is `node.range`, except that a `File` root replaces the whole
1236
1246
  * text (`[0, text.length]`) whatever `node` is, which allows whole-file
1237
1247
  * regeneration. `options` is passed to `printSync` unchanged.
1248
+ * A `File` root can cover deferred heredocs outside a subtree. If a
1249
+ * carriage return may belong to a heredoc, printing is refused even for a
1250
+ * `File` root because the parser can interpret it as part of a line ending.
1251
+ * The printer must also preserve the positions of carriage returns in
1252
+ * the replaced text, including inside quoted words.
1238
1253
  *
1239
1254
  * The printer formats; it does not replay the source. Its output starts at
1240
1255
  * column 0 and indents nested lines with upstream's indentation (tabs by
@@ -1261,9 +1276,12 @@ export declare interface ShellRuleVisitor extends ShellTypedListeners {
1261
1276
  * @throws TypeError with `ESLINT_SH_FOREIGN_VIEW_NODE` when `node` has no original record in this file (see
1262
1277
  * {@link ShellSourceCode.getEditableSyntax}), when `edited` is not a
1263
1278
  * printable root (`ESLINT_SH_PRINT_ROOT`; the message names its type), or when the printer's output
1264
- * is not valid UTF-8 (`ESLINT_SH_PRINT_ENCODING`), or the edited syntax contains literal vertical tabs or
1265
- * form feeds that the printer cannot preserve (`ESLINT_SH_PRINT_UNSAFE_TEXT`). Non-UTF-8 output comes back
1266
- * from `printSync` as a `Uint8Array` and is never decoded lossily into a fix.
1279
+ * is not valid UTF-8 (`ESLINT_SH_PRINT_ENCODING`), or a subtree replacement cannot cover the original
1280
+ * or edited heredocs (`ESLINT_SH_PRINT_HEREDOC_RANGE`), or the replacement could
1281
+ * lose a carriage return in a heredoc (`ESLINT_SH_PRINT_HEREDOC_TEXT`), or the
1282
+ * positions of carriage returns in the replacement differ from the source
1283
+ * (`ESLINT_SH_PRINT_UNSAFE_TEXT`). Non-UTF-8 output comes back from `printSync`
1284
+ * as a `Uint8Array` and is never decoded lossily into a fix.
1267
1285
  * @throws `PrintError` (`SH_AST_SYNTAX_PRINT`), `PrintPanicError` (`SH_AST_SYNTAX_PRINT_PANIC`),
1268
1286
  * or `InputError` (`SH_AST_SYNTAX_INPUT`), passed through unchanged from sh-ast, when upstream's
1269
1287
  * printer fails for `edited` or `options`.
@@ -1311,6 +1329,8 @@ export declare interface ShellRuleVisitor extends ShellTypedListeners {
1311
1329
  line: number;
1312
1330
  column: number;
1313
1331
  };
1332
+ /** Returns inventory facts for parsed command arguments. @internal */
1333
+ getCommandArgumentFacts(callExpr: ShellNodeOf<'CallExpr'>): readonly WordFacts[] | undefined;
1314
1334
  /**
1315
1335
  * Returns the parent of `node`, or `undefined` for the root `File` node
1316
1336
  * (or any node visited before `traverse()` has run once). ESLint always
@@ -1401,6 +1421,8 @@ export declare interface TransparentWrappersBindingContext {
1401
1421
  readonly sourceCode: ShellSourceCode;
1402
1422
  }
1403
1423
 
1424
+ export { WordFacts }
1425
+
1404
1426
  export { WordResolution }
1405
1427
 
1406
1428
  /**
@@ -1,6 +1,9 @@
1
- import type { Argv0Resolution, CommandUncertainty, CommandContext, CommandSite, ResolveArgv0Options, WordResolution } from 'sh-analysis';
1
+ import type { Argv0ChainWord, Argv0Resolution, CommandUncertainty, CommandContext, CommandSite, ResolveArgv0Options, WordFacts, WordResolution } from 'sh-analysis';
2
2
  import type { CallExpr } from 'sh-ast';
3
+ import type { ShellDialect } from './shell-language-options.js';
3
4
  import type { ShellFile, ShellNode, ShellNodeOf } from './syntax-view.js';
5
+ /** Inventory requested with the source dialect always includes facts. @internal */
6
+ export type DialectCommandSite = CommandSite & Required<Pick<CommandSite, 'dialect' | 'argvFacts'>>;
4
7
  /**
5
8
  * Every command site in one parsed file, from a single `enumerateCommands`
6
9
  * call. `sites` keeps analysis's own list and order (source order); `byNode`
@@ -10,10 +13,10 @@ import type { ShellFile, ShellNode, ShellNodeOf } from './syntax-view.js';
10
13
  * @internal
11
14
  */
12
15
  export interface CommandSiteIndex {
13
- readonly sites: readonly CommandSite[];
16
+ readonly sites: readonly DialectCommandSite[];
14
17
  /** Opaque execution boundaries retained alongside represented commands. */
15
18
  readonly uncertainties: readonly CommandUncertainty[];
16
- readonly byNode: ReadonlyMap<CallExpr, CommandSite>;
19
+ readonly byNode: ReadonlyMap<CallExpr, DialectCommandSite>;
17
20
  }
18
21
  /**
19
22
  * One command invocation in a linted shell file, in lint-view terms: an
@@ -48,7 +51,8 @@ export interface ShellCommandSite {
48
51
  * The path from the file root to this command, outermost frame first,
49
52
  * exactly as `sh-analysis` reports it. For example, `date` in
50
53
  * `f() { echo "$(date)"; }` has
51
- * `[{ kind: 'function', name: 'f' }, { kind: 'cmdSubst' }]`.
54
+ * `[{ kind: 'function', names: ['f'] }, { kind: 'cmdSubst' }]`.
55
+ * Function frames list names in declaration order. Anonymous functions have an empty list.
52
56
  */
53
57
  readonly context: readonly CommandContext[];
54
58
  /** The command word (`argv[0]`) resolved with `{ context: 'command-argument' }`. */
@@ -59,6 +63,8 @@ export interface ShellCommandSite {
59
63
  * assignments are not part of argv.
60
64
  */
61
65
  readonly argv: readonly WordResolution[];
66
+ /** Word facts for the same original argv positions, using the parsed dialect. */
67
+ readonly argvFacts: readonly WordFacts[];
62
68
  /**
63
69
  * Follows this command's argv0 through transparent wrappers (`env`, `sudo`,
64
70
  * `nohup`, `exec`, …) and returns `sh-analysis`'s `resolveArgv0`
@@ -66,7 +72,7 @@ export interface ShellCommandSite {
66
72
  * `ShellSourceCode.resolveInvokedCommand(node, options)`; both read the
67
73
  * same per-file index.
68
74
  *
69
- * @param options - Forwarded to `resolveArgv0` unchanged.
75
+ * @param options - Wrapper and interpreter settings. Resolution uses the parsed dialect.
70
76
  * `transparentWrappers` replaces `sh-analysis`'s
71
77
  * `DEFAULT_TRANSPARENT_WRAPPERS`; spread the defaults into the array to
72
78
  * extend them instead.
@@ -78,6 +84,8 @@ export interface ShellCommandSite {
78
84
  */
79
85
  resolveInvokedCommand(options?: ResolveArgv0Options): Argv0Resolution;
80
86
  }
87
+ /** The known basename of a real chain word at its original argv position. @internal */
88
+ export declare function commandBasename(site: ShellCommandSite, word: Argv0ChainWord, index: number): string | null;
81
89
  /**
82
90
  * An opaque executable construct projected onto the original ESLint view.
83
91
  * Its presence limits inventory completeness; it does not assert a hidden command.
@@ -124,7 +132,9 @@ export interface ShellCommandInventory {
124
132
  * partial index would silently omit real commands, so callers fail closed.
125
133
  * @internal
126
134
  */
127
- export declare function buildCommandSiteIndex(file: ShellFile): CommandSiteIndex;
135
+ export declare function buildCommandSiteIndex(file: ShellFile, dialect: ShellDialect): CommandSiteIndex;
136
+ /** Resolves wrappers using the same dialect and facts as command enumeration. @internal */
137
+ export declare function resolveSiteArgv0(site: DialectCommandSite, options?: ResolveArgv0Options): Argv0Resolution;
128
138
  /**
129
139
  * Re-expresses every site in `index` in lint-view terms, in analysis's order.
130
140
  * Each `node` comes from the syntax → view association recorded when `file`
@@ -9,7 +9,16 @@
9
9
  * propagate unchanged instead of becoming partial inventories or parser errors.
10
10
  */
11
11
  import { enumerateCommands, resolveArgv0 } from 'sh-analysis';
12
- import { syntaxForNode, viewForSyntax, withoutCrlfCarriageReturn } from './syntax-view.js';
12
+ import { syntaxForNode, viewForSyntax } from './syntax-view.js';
13
+ import { analysisDialect, withLfWordFacts } from './word-resolution.js';
14
+ /** The known basename of a real chain word at its original argv position. @internal */
15
+ export function commandBasename(site, word, index) {
16
+ const facts = site.argvFacts.at(index);
17
+ // An unresolved wrapper flag or embedded program is not an observed command word.
18
+ if (word !== facts?.resolution || !facts.basename.known)
19
+ return null;
20
+ return facts.basename.text;
21
+ }
13
22
  /**
14
23
  * Builds the {@link CommandSiteIndex} for a whole parsed file with a single
15
24
  * `enumerateCommands` call over the file's original syntax. Each site's
@@ -32,20 +41,17 @@ import { syntaxForNode, viewForSyntax, withoutCrlfCarriageReturn } from './synta
32
41
  * partial index would silently omit real commands, so callers fail closed.
33
42
  * @internal
34
43
  */
35
- export function buildCommandSiteIndex(file) {
44
+ export function buildCommandSiteIndex(file, dialect) {
36
45
  const syntax = syntaxForNode(file);
37
46
  if (syntax?.Type !== 'File') {
38
47
  throw Object.assign(new TypeError('expected a parsed shell File from this language adapter'), {
39
48
  code: 'ESLINT_SH_FILE_NODE',
40
49
  });
41
50
  }
42
- const inventory = enumerateCommands(syntax);
51
+ const inventory = enumerateCommands(syntax, { dialect: analysisDialect(dialect) });
43
52
  const sites = Object.freeze(inventory.commands.map((site) => freezeCommandSite(withLfArgv(site))));
44
53
  const uncertainties = Object.freeze(inventory.uncertainties.map((uncertainty) => {
45
- for (const frame of uncertainty.context) {
46
- Object.freeze(frame);
47
- }
48
- Object.freeze(uncertainty.context);
54
+ freezeCommandContext(uncertainty.context);
49
55
  return Object.freeze(uncertainty);
50
56
  }));
51
57
  return { sites, uncertainties, byNode: new Map(sites.map((site) => [site.node, site])) };
@@ -58,11 +64,18 @@ export function buildCommandSiteIndex(file) {
58
64
  * chains from `site.argv` and `getCommandName` reads `site.argv0`.
59
65
  */
60
66
  function withLfArgv(site) {
67
+ const { dialect, argvFacts: observed } = site;
68
+ if (dialect === undefined || observed === undefined) {
69
+ throw new Error('dialect-aware command inventory must include word facts');
70
+ }
61
71
  const words = site.node.Args ?? [];
62
- const argv = site.argv.map((resolution, index) => withoutCrlfCarriageReturn(words[index] ?? null, resolution));
63
- if (argv.every((resolution, index) => resolution === site.argv[index]))
64
- return site;
65
- return { ...site, argv0: argv[0], argv };
72
+ const argvFacts = observed.map((facts, index) => withLfWordFacts(words[index] ?? null, facts));
73
+ const argv = argvFacts.map(({ resolution }) => resolution);
74
+ return { ...site, dialect, argvFacts, argv0: argv[0], argv };
75
+ }
76
+ /** Resolves wrappers using the same dialect and facts as command enumeration. @internal */
77
+ export function resolveSiteArgv0(site, options) {
78
+ return resolveArgv0(site, { ...options, dialect: site.dialect });
66
79
  }
67
80
  /**
68
81
  * Freezes the data a rule can reach through `site`: the site, its `context`
@@ -73,19 +86,32 @@ function withLfArgv(site) {
73
86
  * Freezing in place, instead of copying, keeps every value identical to what
74
87
  * analysis returned. That is safe because `enumerateCommands` builds these
75
88
  * objects fresh on each call, and nothing in `sh-analysis` writes to them
76
- * after it returns: `resolveArgv0` only reads a site. A frame's fields are
77
- * primitives or source text, so freezing each frame shallowly is complete.
89
+ * after it returns: `resolveArgv0` only reads a site.
78
90
  */
79
91
  function freezeCommandSite(site) {
80
- for (const frame of site.context)
81
- Object.freeze(frame);
82
- Object.freeze(site.context);
92
+ freezeCommandContext(site.context);
83
93
  for (const word of site.argv)
84
94
  Object.freeze(word);
95
+ for (const facts of site.argvFacts) {
96
+ Object.freeze(facts.features);
97
+ Object.freeze(facts.fields);
98
+ Object.freeze(facts.basename);
99
+ Object.freeze(facts);
100
+ }
101
+ Object.freeze(site.argvFacts);
85
102
  Object.freeze(site.argv);
86
103
  Object.freeze(site.argv0);
87
104
  return Object.freeze(site);
88
105
  }
106
+ /** Freezes the shared context frames and their function name lists. */
107
+ function freezeCommandContext(context) {
108
+ for (const frame of context) {
109
+ if (frame.kind === 'function')
110
+ Object.freeze(frame.names);
111
+ Object.freeze(frame);
112
+ }
113
+ Object.freeze(context);
114
+ }
89
115
  /**
90
116
  * Re-expresses every site in `index` in lint-view terms, in analysis's order.
91
117
  * Each `node` comes from the syntax → view association recorded when `file`
@@ -112,7 +138,8 @@ export function viewCommandSites(file, index) {
112
138
  context: site.context,
113
139
  argv0: site.argv0,
114
140
  argv: site.argv,
115
- resolveInvokedCommand: (options) => resolveArgv0(site, options),
141
+ argvFacts: site.argvFacts,
142
+ resolveInvokedCommand: (options) => resolveSiteArgv0(site, options),
116
143
  });
117
144
  }));
118
145
  }
@@ -1,14 +1,20 @@
1
1
  /**
2
2
  * Line-break handling shared by rules, so a CRLF file lints like its LF
3
- * equivalent: an edit that writes a line break uses the file's own style, and
3
+ * equivalent: an edit that writes a line break uses the edited line's style, and
4
4
  * report text quoting source never prints the `\r` of a `\r\n`.
5
5
  */
6
6
  /**
7
- * The line break an edit to `text` writes: the file's first line break, so a
8
- * CRLF file stays CRLF, or `\n` when `text` has none.
7
+ * The terminator of the line containing `offset`, or LF for an unterminated
8
+ * line. Only LF ends a shell source line, with an optional preceding CR.
9
9
  * @internal
10
10
  */
11
- export declare function lineBreakOf(text: string): string;
11
+ export declare function lineBreakOf(text: string, offset: number): '\n' | '\r\n';
12
+ /**
13
+ * A line break after generated shell code. A comment keeps CR out of the
14
+ * preceding token when the edited line ends with CRLF.
15
+ * @internal
16
+ */
17
+ export declare function shellLineBreakOf(text: string, offset: number): string;
12
18
  /**
13
19
  * `excerpt` (source text a message quotes) with each `\r\n` written as `\n`,
14
20
  * so a quoted multi-line construct reads the same in a CRLF file as in its LF
@@ -1,15 +1,24 @@
1
1
  /**
2
2
  * Line-break handling shared by rules, so a CRLF file lints like its LF
3
- * equivalent: an edit that writes a line break uses the file's own style, and
3
+ * equivalent: an edit that writes a line break uses the edited line's style, and
4
4
  * report text quoting source never prints the `\r` of a `\r\n`.
5
5
  */
6
6
  /**
7
- * The line break an edit to `text` writes: the file's first line break, so a
8
- * CRLF file stays CRLF, or `\n` when `text` has none.
7
+ * The terminator of the line containing `offset`, or LF for an unterminated
8
+ * line. Only LF ends a shell source line, with an optional preceding CR.
9
9
  * @internal
10
10
  */
11
- export function lineBreakOf(text) {
12
- return /\r\n|\n|\r/u.exec(text)?.[0] ?? '\n';
11
+ export function lineBreakOf(text, offset) {
12
+ const end = text.indexOf('\n', offset);
13
+ return end > 0 && text[end - 1] === '\r' ? '\r\n' : '\n';
14
+ }
15
+ /**
16
+ * A line break after generated shell code. A comment keeps CR out of the
17
+ * preceding token when the edited line ends with CRLF.
18
+ * @internal
19
+ */
20
+ export function shellLineBreakOf(text, offset) {
21
+ return lineBreakOf(text, offset) === '\r\n' ? ' #\r\n' : '\n';
13
22
  }
14
23
  /**
15
24
  * `excerpt` (source text a message quotes) with each `\r\n` written as `\n`,
@@ -2,6 +2,8 @@ import type { File, Language, OkParseResult, ParseResult } from '@eslint/core';
2
2
  import { ShellSourceCode } from './shell-source-code.js';
3
3
  import type { ShellFile, ShellNode } from './syntax-view.js';
4
4
  import { type NormalizedShellLanguageOptions, type ShellLanguageOptions } from './shell-language-options.js';
5
+ /** Whether the file had a BOM before ESLint stripped it. @internal */
6
+ export declare function sourceHasBOM(sourceCode: ShellSourceCode): boolean;
5
7
  /**
6
8
  * `ShellLanguage` — the `@eslint/core` `Language` implementation for shell
7
9
  * scripts. Registered by the plugin as `languages.sh`, so consumers select
@@ -9,6 +9,12 @@ import { adaptSyntaxFile, shellVisitorKeys } from './syntax-view.js';
9
9
  import { normalizeShellLanguageOptions, validateShellLanguageOptions, } from './shell-language-options.js';
10
10
  /** ESLint declares mutable visitor arrays; give it its own copy of the shared consumer relationships. */
11
11
  const mutableShellVisitorKeys = Object.fromEntries(Object.entries(shellVisitorKeys).map(([type, keys]) => [type, [...keys]]));
12
+ /** ESLint tracks the BOM separately from the source text and its coordinates. */
13
+ const sourcesWithBOM = new WeakSet();
14
+ /** Whether the file had a BOM before ESLint stripped it. @internal */
15
+ export function sourceHasBOM(sourceCode) {
16
+ return sourcesWithBOM.has(sourceCode);
17
+ }
12
18
  /**
13
19
  * Strip the exact upstream filename/position prefix ESLint renders separately.
14
20
  * Upstream formats saturated line/column components as `?`; the source byte
@@ -161,7 +167,7 @@ export class ShellLanguage {
161
167
  * through `sourceCode.dialect` / `sourceCode.minBashVersion`.
162
168
  */
163
169
  createSourceCode(file, parseResult, context) {
164
- return new ShellSourceCode({
170
+ const sourceCode = new ShellSourceCode({
165
171
  text: file.body,
166
172
  ast: parseResult.ast,
167
173
  directivePrefix: context.languageOptions.directivePrefix ?? 'eslint',
@@ -170,5 +176,8 @@ export class ShellLanguage {
170
176
  ? {}
171
177
  : { minBashVersion: context.languageOptions.minBashVersion }),
172
178
  });
179
+ if (file.bom)
180
+ sourcesWithBOM.add(sourceCode);
181
+ return sourceCode;
173
182
  }
174
183
  }