@eslint-sh/eslint-plugin 0.12.0 → 0.14.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 (83) hide show
  1. package/README.md +32 -12
  2. package/dist/api.d.ts +11 -1
  3. package/dist/api.js +8 -0
  4. package/dist/command-harvest/harvest-commands.d.ts +5 -3
  5. package/dist/command-harvest/harvest-commands.js +34 -12
  6. package/dist/eslint-plugin-api.d.ts +65 -12
  7. package/dist/language/command-resolution.d.ts +24 -6
  8. package/dist/language/command-resolution.js +44 -17
  9. package/dist/language/shell-language.js +2 -0
  10. package/dist/language/shell-source-code.d.ts +29 -11
  11. package/dist/language/shell-source-code.js +35 -26
  12. package/dist/language/word-resolution.d.ts +18 -12
  13. package/dist/language/word-resolution.js +133 -3
  14. package/dist/processors/disable-justification.d.ts +20 -0
  15. package/dist/processors/disable-justification.js +124 -0
  16. package/dist/rules/compat/bash-builtin-destination.d.ts +19 -0
  17. package/dist/rules/compat/bash-builtin-destination.js +83 -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 +52 -20
  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 +55 -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 +257 -71
  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 +29 -17
  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 +65 -25
  42. package/dist/rules/no-unused-declarations.js +51 -19
  43. package/dist/rules/prefer-local.js +136 -16
  44. package/dist/rules/require-strict-mode.d.ts +2 -2
  45. package/dist/rules/require-strict-mode.js +27 -18
  46. package/dist/rules/require-tty-guard.d.ts +2 -0
  47. package/dist/rules/require-tty-guard.js +211 -45
  48. package/dist/rules/set-options.d.ts +3 -1
  49. package/dist/rules/set-options.js +5 -1
  50. package/dist/rules/strict-mode-prologue.d.ts +9 -2
  51. package/dist/rules/strict-mode-prologue.js +45 -8
  52. package/docs/custom-rule-tutorial.md +148 -155
  53. package/docs/disable-justification.md +71 -0
  54. package/docs/error-codes.md +4 -0
  55. package/docs/examples/eslint.config.js +11 -0
  56. package/docs/examples/no-curl-in-functions-rule.mjs +20 -23
  57. package/docs/examples/no-listed-commands-rule.ts +19 -19
  58. package/docs/examples/no-rm-rf-rule.mjs +33 -62
  59. package/docs/examples/no-sample-command-rule.mjs +33 -0
  60. package/docs/reading-nodes.md +26 -1
  61. package/docs/rules/README.md +4 -4
  62. package/docs/rules/compat/no-mapfile.md +14 -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 +8 -2
  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 +2 -1
  72. package/docs/rules/no-secret-flags.md +22 -2
  73. package/docs/rules/no-unchecked-cd.md +3 -1
  74. package/docs/rules/no-undeclared-commands.md +1 -1
  75. package/docs/rules/no-unused-declarations.md +10 -6
  76. package/docs/rules/prefer-local.md +4 -0
  77. package/docs/rules/require-network-wrapper.md +1 -1
  78. package/docs/rules/require-strict-mode.md +19 -11
  79. package/docs/rules/require-tty-guard.md +26 -4
  80. package/docs/rules-about-commands.md +78 -0
  81. package/docs/selectors.md +8 -4
  82. package/docs/wrapper-rules.md +1 -1
  83. package/package.json +4 -4
@@ -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,5 +1,6 @@
1
1
  /** Adapts upstream parsing and diagnostics to ESLint's synchronous Language contract. */
2
2
  import { LangError, ParseError, ShParseMaxDepthError, parseWithPositionsSync, } from 'sh-ast';
3
+ import { collectDisableJustificationFindings } from '../processors/disable-justification.js';
3
4
  import { SHELL_VARIANTS } from '../shell-dialect.js';
4
5
  import { nonShellFileError } from './non-shell-file-guard.js';
5
6
  import { matchesSelectorClass as matchesShellSelectorClass } from './selector-classes.js';
@@ -178,6 +179,7 @@ export class ShellLanguage {
178
179
  });
179
180
  if (file.bom)
180
181
  sourcesWithBOM.add(sourceCode);
182
+ collectDisableJustificationFindings(file.path, sourceCode);
181
183
  return sourceCode;
182
184
  }
183
185
  }
@@ -10,7 +10,7 @@ import { TextSourceCodeBase } from '@eslint/plugin-kit';
10
10
  import type { ShellFile as ShFile, ShellNode as ShNode, ShellNodeOf, ShellComment } from './syntax-view.js';
11
11
  import type { Directive as IDirective, FileProblem, RulesConfig, SourceLocation, TraversalStep } from '@eslint/core';
12
12
  import type { Node as SyntaxNode, PrintOptions, SyntaxPos } from 'sh-ast';
13
- import type { Argv0Resolution, ResolveArgv0Options, ResolveWordOptions, WordResolution } from 'sh-analysis';
13
+ import type { Argv0Resolution, ResolveArgv0Options, ResolveWordOptions, WordFacts, WordResolution } from 'sh-analysis';
14
14
  import type { ShellDialect, ShellLanguageOptions } from './shell-language-options.js';
15
15
  import type { ShellCommandInventory } from './command-resolution.js';
16
16
  /**
@@ -126,10 +126,15 @@ export declare class ShellSourceCode extends TextSourceCodeBase<{
126
126
  * `sh-analysis` owns static-word interpretation and dynamic reasons; this
127
127
  * method supplies the lint tree's position-based policy, without executing shell.
128
128
  *
129
- * Without explicit options, `CallExpr.args` use command-argument context, so
130
- * `PATH=a:~/bin` is literal there. Other positions retain the analyzer's
131
- * conservative default, including tilde expansion after an unquoted colon.
132
- * Explicit options are forwarded unchanged, even when empty.
129
+ * Without explicit options, `CallExpr.args` use command-argument context.
130
+ * An ordinary argument such as `a:~/bin` is literal in that context, while
131
+ * `PATH=a:~/bin` is dynamic because Bash can expand the tilde in an
132
+ * assignment-shaped argument. Other positions use the analyzer's
133
+ * conservative default, which also considers assignment-value expansion.
134
+ * Explicit options override the context defaults. Resolution uses the parsed dialect.
135
+ * Since sh-analysis 0.3, a top-level escaped literal can return `unsupported`
136
+ * when the analyzer receives no context. For the assignment value in
137
+ * `label=a\ b`, pass `{ context: 'assignment-value' }` to resolve `a b`.
133
138
  *
134
139
  * @param word - A parsed Word from the lint view.
135
140
  * @param options - Explicit analysis policy overriding grammar defaults.
@@ -178,10 +183,11 @@ export declare class ShellSourceCode extends TextSourceCodeBase<{
178
183
  * assignment-only statement such as `FOO=1`).
179
184
  *
180
185
  * Delegates to `resolveArgv0` with the `CommandSite` that `enumerateCommands`
181
- * reports for this `CallExpr` in this file, so it inherits that function's
182
- * guarantee that an unknowable word is never guessed through. Read the
183
- * effective command's name as
184
- * `res.effective.static ? res.effective.text : null`.
186
+ * reports for this `CallExpr` in this file. A wrapper that accepts assignments
187
+ * can skip a fixed scalar assignment prefix when the operand is known to
188
+ * occupy one field, even if the value is dynamic. For example,
189
+ * `env PATH=a:~/bin printf hi` resolves to `printf`. Read the effective
190
+ * command's name as `res.effective.static ? res.effective.text : null`.
185
191
  * `sudo -u x "$prog"` and `exec "$@"` have a non-static `effective` with
186
192
  * reason `expansion`; `env -S '…'` and `bash -c '…'` have reason
187
193
  * `embedded-command`; `chain`
@@ -190,7 +196,14 @@ export declare class ShellSourceCode extends TextSourceCodeBase<{
190
196
  * {@link ShellSourceCode.getCommandInventory} reports it). When `effective` is
191
197
  * static, the effective command's arguments are
192
198
  * `argv.slice(chainIndices.at(-1)! + 1)`: every entry after the effective
193
- * command's own index. For an interpreter command string the final chain
199
+ * command's own index. For basename matching, check that `effective` is
200
+ * the same object as `argvFacts[index].resolution` on the inventory site.
201
+ * A non-static word reached through a wrapper may still be an operand
202
+ * whose role is unresolved. A known `basename` supplies its `text` even
203
+ * with a dynamic directory.
204
+ * If the basename fact is unknown and `effective` is static, its `text`
205
+ * supplies the whole path.
206
+ * For an interpreter command string the final chain
194
207
  * index instead locates the selector flag; the interpreter is in `chain.at(-2)`.
195
208
  * `embeddedCommandInterpreters: []` retains the interpreter as the static
196
209
  * effective command when a policy needs program identity. Utility wrappers
@@ -204,7 +217,7 @@ export declare class ShellSourceCode extends TextSourceCodeBase<{
204
217
  * index would silently omit real commands.
205
218
  *
206
219
  * @param callExpr - A parsed `CallExpr` node from this file's lint tree.
207
- * @param options - Forwarded to `resolveArgv0` unchanged.
220
+ * @param options - Wrapper and interpreter settings. Resolution uses the parsed dialect.
208
221
  * `transparentWrappers` replaces `sh-analysis`'s
209
222
  * `DEFAULT_TRANSPARENT_WRAPPERS`; spread the defaults into the array to
210
223
  * extend them instead.
@@ -398,6 +411,8 @@ export declare class ShellSourceCode extends TextSourceCodeBase<{
398
411
  line: number;
399
412
  column: number;
400
413
  };
414
+ /** Returns inventory facts for parsed command arguments. @internal */
415
+ getCommandArgumentFacts(callExpr: ShellNodeOf<'CallExpr'>): readonly WordFacts[] | undefined;
401
416
  /**
402
417
  * Returns the parent of `node`, or `undefined` for the root `File` node
403
418
  * (or any node visited before `traverse()` has run once). ESLint always
@@ -431,6 +446,9 @@ export declare class ShellSourceCode extends TextSourceCodeBase<{
431
446
  * source as the named ecosystem precedent), generalized to a configurable
432
447
  * prefix instead of the hardcoded `"eslint"` label.
433
448
  *
449
+ * Diagnostics about a directive should use the node's location. Its range may extend beyond the
450
+ * comment so ESLint can remove an unused directive cleanly.
451
+ *
434
452
  * Unlike `JSONSourceCode` (whose block comments can span multiple
435
453
  * physical lines, making `<prefix>-disable-line` spanning lines a real,
436
454
  * reportable problem), mvdan/sh's `#` line comments cannot contain an
@@ -11,9 +11,8 @@ import { isShellComment, projectedComments, projectedCoordinates, someShellNode,
11
11
  import { cloneSyntax } from './syntax-clone.js';
12
12
  import { SourceCoordinates } from './source-coordinates.js';
13
13
  import { DashHdoc, Hdoc, SYNTAX_INTERFACES, printSync } from 'sh-ast';
14
- import { resolveArgv0 } from 'sh-analysis';
15
- import { buildCommandSiteIndex, rawCallExprFor, viewCommandInventory, } from './command-resolution.js';
16
- import { resolveWord } from './word-resolution.js';
14
+ import { buildCommandSiteIndex, rawCallExprFor, resolveSiteArgv0, viewCommandInventory, } from './command-resolution.js';
15
+ import { resolvePublicWord } from './word-resolution.js';
17
16
  /**
18
17
  * Subtree edits must cover the original heredoc extents. The printer emits a
19
18
  * heredoc's body and delimiter even when the parser ends the target at its
@@ -522,10 +521,15 @@ export class ShellSourceCode extends TextSourceCodeBase {
522
521
  * `sh-analysis` owns static-word interpretation and dynamic reasons; this
523
522
  * method supplies the lint tree's position-based policy, without executing shell.
524
523
  *
525
- * Without explicit options, `CallExpr.args` use command-argument context, so
526
- * `PATH=a:~/bin` is literal there. Other positions retain the analyzer's
527
- * conservative default, including tilde expansion after an unquoted colon.
528
- * Explicit options are forwarded unchanged, even when empty.
524
+ * Without explicit options, `CallExpr.args` use command-argument context.
525
+ * An ordinary argument such as `a:~/bin` is literal in that context, while
526
+ * `PATH=a:~/bin` is dynamic because Bash can expand the tilde in an
527
+ * assignment-shaped argument. Other positions use the analyzer's
528
+ * conservative default, which also considers assignment-value expansion.
529
+ * Explicit options override the context defaults. Resolution uses the parsed dialect.
530
+ * Since sh-analysis 0.3, a top-level escaped literal can return `unsupported`
531
+ * when the analyzer receives no context. For the assignment value in
532
+ * `label=a\ b`, pass `{ context: 'assignment-value' }` to resolve `a b`.
529
533
  *
530
534
  * @param word - A parsed Word from the lint view.
531
535
  * @param options - Explicit analysis policy overriding grammar defaults.
@@ -534,7 +538,7 @@ export class ShellSourceCode extends TextSourceCodeBase {
534
538
  * @public
535
539
  */
536
540
  resolveWord(word, options) {
537
- return resolveWord(word, options ?? this.#defaultWordOptions(word));
541
+ return resolvePublicWord(this, word, options);
538
542
  }
539
543
  /**
540
544
  * The text-only form of {@link ShellSourceCode.resolveWord}: returns its text
@@ -551,16 +555,6 @@ export class ShellSourceCode extends TextSourceCodeBase {
551
555
  const resolution = this.resolveWord(word, options);
552
556
  return resolution.static ? resolution.text : null;
553
557
  }
554
- /**
555
- * The `resolveWord` options implied by `word`'s grammar position when the
556
- * caller supplies none: command-argument context for a `CallExpr` argument,
557
- * otherwise `resolveWord`'s own conservative default.
558
- */
559
- #defaultWordOptions(word) {
560
- const parent = this.getParent(word);
561
- const isCommandArgument = parent?.type === 'CallExpr' && Array.isArray(parent.args) && parent.args.includes(word);
562
- return isCommandArgument ? { context: 'command-argument' } : undefined;
563
- }
564
558
  /**
565
559
  * Returns the static text of `callExpr`'s command word (`argv[0]`) as
566
560
  * written, or `null` when that word is dynamic or absent. Transparent
@@ -592,10 +586,11 @@ export class ShellSourceCode extends TextSourceCodeBase {
592
586
  * assignment-only statement such as `FOO=1`).
593
587
  *
594
588
  * Delegates to `resolveArgv0` with the `CommandSite` that `enumerateCommands`
595
- * reports for this `CallExpr` in this file, so it inherits that function's
596
- * guarantee that an unknowable word is never guessed through. Read the
597
- * effective command's name as
598
- * `res.effective.static ? res.effective.text : null`.
589
+ * reports for this `CallExpr` in this file. A wrapper that accepts assignments
590
+ * can skip a fixed scalar assignment prefix when the operand is known to
591
+ * occupy one field, even if the value is dynamic. For example,
592
+ * `env PATH=a:~/bin printf hi` resolves to `printf`. Read the effective
593
+ * command's name as `res.effective.static ? res.effective.text : null`.
599
594
  * `sudo -u x "$prog"` and `exec "$@"` have a non-static `effective` with
600
595
  * reason `expansion`; `env -S '…'` and `bash -c '…'` have reason
601
596
  * `embedded-command`; `chain`
@@ -604,7 +599,14 @@ export class ShellSourceCode extends TextSourceCodeBase {
604
599
  * {@link ShellSourceCode.getCommandInventory} reports it). When `effective` is
605
600
  * static, the effective command's arguments are
606
601
  * `argv.slice(chainIndices.at(-1)! + 1)`: every entry after the effective
607
- * command's own index. For an interpreter command string the final chain
602
+ * command's own index. For basename matching, check that `effective` is
603
+ * the same object as `argvFacts[index].resolution` on the inventory site.
604
+ * A non-static word reached through a wrapper may still be an operand
605
+ * whose role is unresolved. A known `basename` supplies its `text` even
606
+ * with a dynamic directory.
607
+ * If the basename fact is unknown and `effective` is static, its `text`
608
+ * supplies the whole path.
609
+ * For an interpreter command string the final chain
608
610
  * index instead locates the selector flag; the interpreter is in `chain.at(-2)`.
609
611
  * `embeddedCommandInterpreters: []` retains the interpreter as the static
610
612
  * effective command when a policy needs program identity. Utility wrappers
@@ -618,7 +620,7 @@ export class ShellSourceCode extends TextSourceCodeBase {
618
620
  * index would silently omit real commands.
619
621
  *
620
622
  * @param callExpr - A parsed `CallExpr` node from this file's lint tree.
621
- * @param options - Forwarded to `resolveArgv0` unchanged.
623
+ * @param options - Wrapper and interpreter settings. Resolution uses the parsed dialect.
622
624
  * `transparentWrappers` replaces `sh-analysis`'s
623
625
  * `DEFAULT_TRANSPARENT_WRAPPERS`; spread the defaults into the array to
624
626
  * extend them instead.
@@ -631,7 +633,7 @@ export class ShellSourceCode extends TextSourceCodeBase {
631
633
  */
632
634
  resolveInvokedCommand(callExpr, options) {
633
635
  const site = this.#commandSiteFor(callExpr);
634
- return site ? resolveArgv0(site, options) : null;
636
+ return site ? resolveSiteArgv0(site, options) : null;
635
637
  }
636
638
  /**
637
639
  * Returns represented command sites and explicit opaque execution boundaries.
@@ -920,7 +922,7 @@ export class ShellSourceCode extends TextSourceCodeBase {
920
922
  }
921
923
  /** This file's command-site index, built by one `enumerateCommands` call on first use. */
922
924
  #getCommandSiteIndex() {
923
- this.#commandSites ??= buildCommandSiteIndex(this.ast);
925
+ this.#commandSites ??= buildCommandSiteIndex(this.ast, this.dialect);
924
926
  return this.#commandSites;
925
927
  }
926
928
  /**
@@ -932,6 +934,10 @@ export class ShellSourceCode extends TextSourceCodeBase {
932
934
  const raw = rawCallExprFor(callExpr);
933
935
  return this.#getCommandSiteIndex().byNode.get(raw);
934
936
  }
937
+ /** Returns inventory facts for parsed command arguments. @internal */
938
+ getCommandArgumentFacts(callExpr) {
939
+ return this.#commandSiteFor(callExpr)?.argvFacts;
940
+ }
935
941
  /**
936
942
  * Returns the parent of `node`, or `undefined` for the root `File` node
937
943
  * (or any node visited before `traverse()` has run once). ESLint always
@@ -1013,6 +1019,9 @@ export class ShellSourceCode extends TextSourceCodeBase {
1013
1019
  * source as the named ecosystem precedent), generalized to a configurable
1014
1020
  * prefix instead of the hardcoded `"eslint"` label.
1015
1021
  *
1022
+ * Diagnostics about a directive should use the node's location. Its range may extend beyond the
1023
+ * comment so ESLint can remove an unused directive cleanly.
1024
+ *
1016
1025
  * Unlike `JSONSourceCode` (whose block comments can span multiple
1017
1026
  * physical lines, making `<prefix>-disable-line` spanning lines a real,
1018
1027
  * reportable problem), mvdan/sh's `#` line comments cannot contain an
@@ -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,20 @@
1
+ import type { Processor } from '@eslint/core';
2
+ import type { ShellSourceCode } from '../language/shell-source-code.js';
3
+ /**
4
+ * Uses the actual linted source and its language options. Findings are held
5
+ * outside ESLint's rule pass and appended after suppression and unused-directive
6
+ * accounting. The comment location is independent of the unused fix range.
7
+ *
8
+ * @internal
9
+ */
10
+ export declare function collectDisableJustificationFindings(filename: string, sourceCode: ShellSourceCode): void;
11
+ /**
12
+ * Creates a shell processor that requires reasons on inline disable directives.
13
+ * Use with `language: 'sh/sh'`. Omit `rules` to check all directives, or
14
+ * supply exact ESLint rule IDs or literal prefixes ending in `*`.
15
+ *
16
+ * @public
17
+ */
18
+ export declare function createDisableJustificationProcessor(options?: {
19
+ readonly rules?: readonly string[];
20
+ }): Processor;