@eslint-sh/eslint-plugin 0.10.1 → 0.12.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 (34) hide show
  1. package/dist/command-harvest/harvest-commands.d.ts +6 -2
  2. package/dist/command-harvest/harvest-commands.js +13 -6
  3. package/dist/eslint-plugin-api.d.ts +11 -3
  4. package/dist/language/line-breaks.d.ts +10 -4
  5. package/dist/language/line-breaks.js +14 -5
  6. package/dist/language/shell-language.d.ts +2 -0
  7. package/dist/language/shell-language.js +10 -1
  8. package/dist/language/shell-source-code.d.ts +11 -3
  9. package/dist/language/shell-source-code.js +102 -30
  10. package/dist/rules/no-masked-exit-status.js +5 -29
  11. package/dist/rules/no-unused-declarations.js +81 -16
  12. package/dist/rules/prefer-local.js +10 -36
  13. package/dist/rules/require-shebang.js +23 -21
  14. package/dist/rules/require-strict-mode.js +11 -8
  15. package/dist/rules/require-tty-guard.js +8 -5
  16. package/dist/rules/set-options.d.ts +2 -15
  17. package/dist/rules/set-options.js +12 -44
  18. package/dist/rules/shebang-interpreter.d.ts +33 -10
  19. package/dist/rules/shebang-interpreter.js +522 -53
  20. package/dist/rules/shebang-matches-dialect.js +4 -4
  21. package/dist/rules/variable-reads.d.ts +12 -0
  22. package/dist/rules/variable-reads.js +31 -0
  23. package/docs/custom-rule-tutorial.md +9 -3
  24. package/docs/error-codes.md +2 -1
  25. package/docs/rules/README.md +1 -1
  26. package/docs/rules/no-masked-exit-status.md +2 -0
  27. package/docs/rules/no-unused-declarations.md +9 -4
  28. package/docs/rules/prefer-local.md +11 -33
  29. package/docs/rules/require-shebang.md +46 -3
  30. package/docs/rules/require-strict-mode.md +23 -6
  31. package/docs/rules/require-tty-guard.md +1 -0
  32. package/docs/rules/shebang-matches-dialect.md +3 -0
  33. package/docs/shellcheck.md +1 -1
  34. package/package.json +3 -3
@@ -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(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,
@@ -65,7 +69,7 @@ export declare function definedFunctionNames(sourceCode: ShellSourceCode): Reado
65
69
  *
66
70
  * - dynamic words, which name no knowable command;
67
71
  * - builtins of the file's dialect (`sourceCode.dialect`);
68
- * - functions the file defines anywhere.
72
+ * - functions the file defines anywhere, subject to `options.excludeFunction`.
69
73
  *
70
74
  * @throws `ShAnalyzeMaxDepthError` (`SH_ANALYSIS_MAX_DEPTH`, from `sh-analysis`) when the file's
71
75
  * nesting exceeds analysis's recursion guard: a partial harvest would miss
@@ -30,6 +30,13 @@
30
30
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
31
31
  import { walkShell } from '../language/syntax-view.js';
32
32
  import { builtinsForDialect } from './builtins/index.js';
33
+ /** The names introduced by one declaration, including zsh's multi-name form. @internal */
34
+ export function functionNames(node) {
35
+ const names = node.names.map((lit) => lit.value);
36
+ if (node.name)
37
+ names.push(node.name.value);
38
+ return names;
39
+ }
33
40
  /**
34
41
  * The names of every function the file defines, anywhere in it (top level,
35
42
  * nested in another function, inside a conditional, …). Position is not read,
@@ -45,10 +52,8 @@ export function definedFunctionNames(sourceCode) {
45
52
  walkShell(sourceCode.ast, (node) => {
46
53
  if (node.type !== 'FuncDecl')
47
54
  return;
48
- if (node.name)
49
- names.add(node.name.value);
50
- for (const lit of node.names)
51
- names.add(lit.value);
55
+ for (const name of functionNames(node))
56
+ names.add(name);
52
57
  });
53
58
  return names;
54
59
  }
@@ -69,7 +74,7 @@ function wordNodeAt(site, index) {
69
74
  *
70
75
  * - dynamic words, which name no knowable command;
71
76
  * - builtins of the file's dialect (`sourceCode.dialect`);
72
- * - functions the file defines anywhere.
77
+ * - functions the file defines anywhere, subject to `options.excludeFunction`.
73
78
  *
74
79
  * @throws `ShAnalyzeMaxDepthError` (`SH_ANALYSIS_MAX_DEPTH`, from `sh-analysis`) when the file's
75
80
  * nesting exceeds analysis's recursion guard: a partial harvest would miss
@@ -89,7 +94,9 @@ export function harvestCommands(sourceCode, options = {}) {
89
94
  if (!word.static)
90
95
  continue;
91
96
  const name = word.text;
92
- if (harvested.has(name) || builtins.has(name) || functions.has(name))
97
+ if (harvested.has(name) || builtins.has(name))
98
+ continue;
99
+ if (functions.has(name) && (options.excludeFunction?.(name, site) ?? true))
93
100
  continue;
94
101
  harvested.set(name, { name, node: wordNodeAt(site, chainIndices[position]), site });
95
102
  }
@@ -1235,6 +1235,11 @@ export declare interface ShellRuleVisitor extends ShellTypedListeners {
1235
1235
  * The range is `node.range`, except that a `File` root replaces the whole
1236
1236
  * text (`[0, text.length]`) whatever `node` is, which allows whole-file
1237
1237
  * regeneration. `options` is passed to `printSync` unchanged.
1238
+ * A `File` root can cover deferred heredocs outside a subtree. If a
1239
+ * carriage return may belong to a heredoc, printing is refused even for a
1240
+ * `File` root because the parser can interpret it as part of a line ending.
1241
+ * The printer must also preserve the positions of carriage returns in
1242
+ * the replaced text, including inside quoted words.
1238
1243
  *
1239
1244
  * The printer formats; it does not replay the source. Its output starts at
1240
1245
  * column 0 and indents nested lines with upstream's indentation (tabs by
@@ -1261,9 +1266,12 @@ export declare interface ShellRuleVisitor extends ShellTypedListeners {
1261
1266
  * @throws TypeError with `ESLINT_SH_FOREIGN_VIEW_NODE` when `node` has no original record in this file (see
1262
1267
  * {@link ShellSourceCode.getEditableSyntax}), when `edited` is not a
1263
1268
  * 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.
1269
+ * is not valid UTF-8 (`ESLINT_SH_PRINT_ENCODING`), or a subtree replacement cannot cover the original
1270
+ * or edited heredocs (`ESLINT_SH_PRINT_HEREDOC_RANGE`), or the replacement could
1271
+ * lose a carriage return in a heredoc (`ESLINT_SH_PRINT_HEREDOC_TEXT`), or the
1272
+ * positions of carriage returns in the replacement differ from the source
1273
+ * (`ESLINT_SH_PRINT_UNSAFE_TEXT`). Non-UTF-8 output comes back from `printSync`
1274
+ * as a `Uint8Array` and is never decoded lossily into a fix.
1267
1275
  * @throws `PrintError` (`SH_AST_SYNTAX_PRINT`), `PrintPanicError` (`SH_AST_SYNTAX_PRINT_PANIC`),
1268
1276
  * or `InputError` (`SH_AST_SYNTAX_INPUT`), passed through unchanged from sh-ast, when upstream's
1269
1277
  * printer fails for `edited` or `options`.
@@ -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
  }
@@ -314,6 +314,11 @@ export declare class ShellSourceCode extends TextSourceCodeBase<{
314
314
  * The range is `node.range`, except that a `File` root replaces the whole
315
315
  * text (`[0, text.length]`) whatever `node` is, which allows whole-file
316
316
  * regeneration. `options` is passed to `printSync` unchanged.
317
+ * A `File` root can cover deferred heredocs outside a subtree. If a
318
+ * carriage return may belong to a heredoc, printing is refused even for a
319
+ * `File` root because the parser can interpret it as part of a line ending.
320
+ * The printer must also preserve the positions of carriage returns in
321
+ * the replaced text, including inside quoted words.
317
322
  *
318
323
  * The printer formats; it does not replay the source. Its output starts at
319
324
  * column 0 and indents nested lines with upstream's indentation (tabs by
@@ -340,9 +345,12 @@ export declare class ShellSourceCode extends TextSourceCodeBase<{
340
345
  * @throws TypeError with `ESLINT_SH_FOREIGN_VIEW_NODE` when `node` has no original record in this file (see
341
346
  * {@link ShellSourceCode.getEditableSyntax}), when `edited` is not a
342
347
  * printable root (`ESLINT_SH_PRINT_ROOT`; the message names its type), or when the printer's output
343
- * is not valid UTF-8 (`ESLINT_SH_PRINT_ENCODING`), or the edited syntax contains literal vertical tabs or
344
- * form feeds that the printer cannot preserve (`ESLINT_SH_PRINT_UNSAFE_TEXT`). Non-UTF-8 output comes back
345
- * from `printSync` as a `Uint8Array` and is never decoded lossily into a fix.
348
+ * is not valid UTF-8 (`ESLINT_SH_PRINT_ENCODING`), or a subtree replacement cannot cover the original
349
+ * or edited heredocs (`ESLINT_SH_PRINT_HEREDOC_RANGE`), or the replacement could
350
+ * lose a carriage return in a heredoc (`ESLINT_SH_PRINT_HEREDOC_TEXT`), or the
351
+ * positions of carriage returns in the replacement differ from the source
352
+ * (`ESLINT_SH_PRINT_UNSAFE_TEXT`). Non-UTF-8 output comes back from `printSync`
353
+ * as a `Uint8Array` and is never decoded lossily into a fix.
346
354
  * @throws `PrintError` (`SH_AST_SYNTAX_PRINT`), `PrintPanicError` (`SH_AST_SYNTAX_PRINT_PANIC`),
347
355
  * or `InputError` (`SH_AST_SYNTAX_INPUT`), passed through unchanged from sh-ast, when upstream's
348
356
  * printer fails for `edited` or `options`.
@@ -7,44 +7,61 @@
7
7
  * their classes, codes and causes.
8
8
  */
9
9
  import { ConfigCommentParser, Directive, TextSourceCodeBase, VisitNodeStep, } from '@eslint/plugin-kit';
10
- import { isShellComment, projectedComments, projectedCoordinates, syntaxForNode, traverseShell, viewForSyntax, walkShell, } from './syntax-view.js';
10
+ import { isShellComment, projectedComments, projectedCoordinates, someShellNode, syntaxForNode, traverseShell, viewForSyntax, walkShell, } from './syntax-view.js';
11
11
  import { cloneSyntax } from './syntax-clone.js';
12
12
  import { SourceCoordinates } from './source-coordinates.js';
13
- import { SYNTAX_INTERFACES, printSync } from 'sh-ast';
13
+ import { DashHdoc, Hdoc, SYNTAX_INTERFACES, printSync } from 'sh-ast';
14
14
  import { resolveArgv0 } from 'sh-analysis';
15
15
  import { buildCommandSiteIndex, rawCallExprFor, viewCommandInventory, } from './command-resolution.js';
16
16
  import { resolveWord } from './word-resolution.js';
17
17
  /**
18
- * Refuses edited syntax whose string or byte values the upstream printer treats as layout.
19
- * Checking the edited tree also catches controls introduced by a rule, without refusing ordinary
20
- * text edits elsewhere in a file. The input filename is metadata, never printer output.
21
- * Iteration tolerates shared/cyclic records; sh-ast still validates
22
- * the printable syntax itself.
18
+ * Subtree edits must cover the original heredoc extents. The printer emits a
19
+ * heredoc's body and delimiter even when the parser ends the target at its
20
+ * header. An empty heredoc has no body position to establish its extent.
23
21
  */
24
- // format.ts's refusePrinterControlCharacters independently guards the formatter's source text.
25
- function refusePrinterControlCharacters(root) {
26
- const pending = [root.Type === 'File' ? { ...root, Name: '' } : root];
22
+ function heredocsFitReplacement(target, edited) {
23
+ const [start, end] = target.range;
24
+ const originalOffsets = new Set();
25
+ const hasDeferredHeredoc = someShellNode(target, (node) => {
26
+ if (node.type !== 'Redirect' || (node.op !== Hdoc && node.op !== DashHdoc))
27
+ return false;
28
+ if (node.hdoc === undefined || node.range[0] < start || node.range[1] > end)
29
+ return true;
30
+ const original = syntaxForNode(node);
31
+ if (original?.Type !== 'Redirect')
32
+ return true;
33
+ originalOffsets.add(original.OpPos.Offset);
34
+ return false;
35
+ });
36
+ if (hasDeferredHeredoc)
37
+ return false;
38
+ // Edited records carry their original positions. Each printed heredoc must
39
+ // match a source redirect within the replacement range.
40
+ const pending = [edited];
27
41
  const seen = new Set();
28
42
  while (pending.length > 0) {
29
43
  const current = pending.pop();
30
- const unsafe = (typeof current === 'string' && /[\v\f]/u.test(current)) ||
31
- (current instanceof Uint8Array && current.some((byte) => byte === 0x0b || byte === 0x0c));
32
- if (unsafe) {
33
- throw Object.assign(new TypeError('cannot print a text fix containing literal vertical tabs and form feeds: ' +
34
- 'the printer changes their value'), { code: 'ESLINT_SH_PRINT_UNSAFE_TEXT' });
35
- }
36
- // A checked byte-valued string is a leaf; its individual numbers are not syntax children.
37
- if (current instanceof Uint8Array) {
44
+ if (current === null ||
45
+ typeof current !== 'object' ||
46
+ current instanceof Uint8Array ||
47
+ seen.has(current)) {
38
48
  continue;
39
49
  }
40
- if (current !== null && typeof current === 'object' && !seen.has(current)) {
41
- seen.add(current);
42
- const children = Object.values(current);
43
- for (const child of children) {
44
- pending.push(child);
50
+ seen.add(current);
51
+ if ('Type' in current && current.Type === 'Redirect') {
52
+ const redirect = current;
53
+ if (redirect.Op === Hdoc || redirect.Op === DashHdoc) {
54
+ const offset = redirect.OpPos?.Offset;
55
+ if (offset === undefined || !originalOffsets.has(offset))
56
+ return false;
45
57
  }
46
58
  }
59
+ const children = Object.values(current);
60
+ for (const child of children) {
61
+ pending.push(child);
62
+ }
47
63
  }
64
+ return true;
48
65
  }
49
66
  /**
50
67
  * Shared instance — `ConfigCommentParser` is stateless (see
@@ -725,6 +742,11 @@ export class ShellSourceCode extends TextSourceCodeBase {
725
742
  * The range is `node.range`, except that a `File` root replaces the whole
726
743
  * text (`[0, text.length]`) whatever `node` is, which allows whole-file
727
744
  * regeneration. `options` is passed to `printSync` unchanged.
745
+ * A `File` root can cover deferred heredocs outside a subtree. If a
746
+ * carriage return may belong to a heredoc, printing is refused even for a
747
+ * `File` root because the parser can interpret it as part of a line ending.
748
+ * The printer must also preserve the positions of carriage returns in
749
+ * the replaced text, including inside quoted words.
728
750
  *
729
751
  * The printer formats; it does not replay the source. Its output starts at
730
752
  * column 0 and indents nested lines with upstream's indentation (tabs by
@@ -751,9 +773,12 @@ export class ShellSourceCode extends TextSourceCodeBase {
751
773
  * @throws TypeError with `ESLINT_SH_FOREIGN_VIEW_NODE` when `node` has no original record in this file (see
752
774
  * {@link ShellSourceCode.getEditableSyntax}), when `edited` is not a
753
775
  * printable root (`ESLINT_SH_PRINT_ROOT`; the message names its type), or when the printer's output
754
- * is not valid UTF-8 (`ESLINT_SH_PRINT_ENCODING`), or the edited syntax contains literal vertical tabs or
755
- * form feeds that the printer cannot preserve (`ESLINT_SH_PRINT_UNSAFE_TEXT`). Non-UTF-8 output comes back
756
- * from `printSync` as a `Uint8Array` and is never decoded lossily into a fix.
776
+ * is not valid UTF-8 (`ESLINT_SH_PRINT_ENCODING`), or a subtree replacement cannot cover the original
777
+ * or edited heredocs (`ESLINT_SH_PRINT_HEREDOC_RANGE`), or the replacement could
778
+ * lose a carriage return in a heredoc (`ESLINT_SH_PRINT_HEREDOC_TEXT`), or the
779
+ * positions of carriage returns in the replacement differ from the source
780
+ * (`ESLINT_SH_PRINT_UNSAFE_TEXT`). Non-UTF-8 output comes back from `printSync`
781
+ * as a `Uint8Array` and is never decoded lossily into a fix.
757
782
  * @throws `PrintError` (`SH_AST_SYNTAX_PRINT`), `PrintPanicError` (`SH_AST_SYNTAX_PRINT_PANIC`),
758
783
  * or `InputError` (`SH_AST_SYNTAX_INPUT`), passed through unchanged from sh-ast, when upstream's
759
784
  * printer fails for `edited` or `options`.
@@ -762,24 +787,71 @@ export class ShellSourceCode extends TextSourceCodeBase {
762
787
  const original = this.#originalSyntaxFor(node);
763
788
  const rootType = printableRootType(edited);
764
789
  const root = edited.Type === 'Stmt' ? { ...edited, Comments: null } : edited;
765
- refusePrinterControlCharacters(root);
790
+ if (rootType !== 'File' &&
791
+ (this.#intersectsEnclosingHeredocHeader(node) || !heredocsFitReplacement(node, root))) {
792
+ throw Object.assign(new TypeError('cannot print a subtree fix without its complete heredocs'), { code: 'ESLINT_SH_PRINT_HEREDOC_RANGE' });
793
+ }
794
+ const target = rootType === 'File' ? this.ast : node;
795
+ if (this.#hasHeredocCarriageReturn(target)) {
796
+ throw Object.assign(new TypeError('cannot print a replacement that may lose a carriage return in a heredoc'), { code: 'ESLINT_SH_PRINT_HEREDOC_TEXT' });
797
+ }
766
798
  const printed = printSync(root, options);
767
799
  if (typeof printed !== 'string') {
768
800
  throw Object.assign(new TypeError('printSync produced output that is not valid UTF-8; a text fix cannot hold it without ' +
769
801
  'lossy decoding'), { code: 'ESLINT_SH_PRINT_ENCODING' });
770
802
  }
771
- if (rootType === 'File') {
772
- return { range: [0, this.text.length], text: printed };
803
+ const range = rootType === 'File' ? [0, this.text.length] : [node.range[0], node.range[1]];
804
+ const source = this.text.slice(...range);
805
+ let originalCr = source.indexOf('\r');
806
+ let printedCr = printed.indexOf('\r');
807
+ while (originalCr !== -1 && originalCr === printedCr) {
808
+ originalCr = source.indexOf('\r', originalCr + 1);
809
+ printedCr = printed.indexOf('\r', printedCr + 1);
810
+ }
811
+ if (originalCr !== printedCr) {
812
+ throw Object.assign(new TypeError('cannot print a replacement that changes the positions of carriage returns'), { code: 'ESLINT_SH_PRINT_UNSAFE_TEXT' });
773
813
  }
774
814
  const dropsTerminator = edited.Type === 'Stmt' &&
775
815
  original.Type === 'Stmt' &&
776
816
  original.Semicolon.IsValid &&
777
817
  !printsOwnTerminator(edited);
778
818
  return {
779
- range: [node.range[0], node.range[1]],
819
+ range,
780
820
  text: dropsTerminator ? `${printed};` : printed,
781
821
  };
782
822
  }
823
+ /** Refuse when the parser may have normalized a carriage return in a heredoc. */
824
+ #hasHeredocCarriageReturn(target) {
825
+ let first;
826
+ return someShellNode(target, (node) => {
827
+ if (node.type !== 'Redirect' || (node.op !== Hdoc && node.op !== DashHdoc))
828
+ return false;
829
+ first ??= this.text.indexOf('\r', target.range[0]);
830
+ if (first === -1)
831
+ return false;
832
+ const carriageReturn = first >= node.range[0] ? first : this.text.indexOf('\r', node.range[0]);
833
+ // A CR can sit at the projected end of the delimiter, or the parser may
834
+ // have treated that delimiter as the start of an empty heredoc and supplied no body extent.
835
+ const end = node.hdoc === undefined ? this.text.length : node.range[1];
836
+ return carriageReturn !== -1 && carriageReturn <= end;
837
+ });
838
+ }
839
+ /** A statement owns its redirects even when their headers sit between command arguments. */
840
+ #intersectsEnclosingHeredocHeader(node) {
841
+ const [start, end] = node.range;
842
+ for (let owner = this.getParent(node); owner !== undefined; owner = this.getParent(owner)) {
843
+ if (owner.type !== 'Stmt')
844
+ continue;
845
+ for (const redirect of owner.redirs) {
846
+ if (redirect.op !== Hdoc && redirect.op !== DashHdoc)
847
+ continue;
848
+ const headerEnd = redirect.word?.range[1] ?? redirect.range[1];
849
+ if (start < headerEnd && redirect.range[0] < end)
850
+ return true;
851
+ }
852
+ }
853
+ return false;
854
+ }
783
855
  /**
784
856
  * `node`'s original record in this file, or a `TypeError` when it has none,
785
857
  * so the printed-fix helpers never copy or replace a range they cannot tie
@@ -87,12 +87,13 @@
87
87
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
88
88
  import { resolveTransparentWrappers } from './resolve-transparent-wrappers.js';
89
89
  import { someShellNode, walkShell } from '../language/syntax-view.js';
90
- import { lineBreakOf } from '../language/line-breaks.js';
90
+ import { shellLineBreakOf } from '../language/line-breaks.js';
91
91
  import { createRule } from './create-rule.js';
92
92
  import { batsErrexitIsOn, isStatusChecked } from './no-unchecked-cd.js';
93
93
  import { setStatementChanges } from './strict-mode-prologue.js';
94
94
  import { applySetOptionChanges, shebangOptionChanges } from './set-options.js';
95
95
  import { BUILTIN_WRAPPER } from './transparent-wrappers.js';
96
+ import { mentionsIdentifier, readsNameHere } from './variable-reads.js';
96
97
  /** Every declaration builtin the rule can check; the default for `builtins`. */
97
98
  const ALL_BUILTINS = ['local', 'declare', 'typeset', 'export', 'readonly'];
98
99
  /** The builtins that create a variable in the enclosing function's scope. */
@@ -157,10 +158,6 @@ export function containsCommandSubstitution(root) {
157
158
  return node.type === 'ProcSubst' ? 'skip' : false;
158
159
  });
159
160
  }
160
- /** Whether `text` mentions `name` as a whole identifier. */
161
- function mentionsIdentifier(text, name) {
162
- return new RegExp(`(?<![A-Za-z0-9_])${name}(?![A-Za-z0-9_])`, 'u').test(text);
163
- }
164
161
  /**
165
162
  * Whether evaluating `node` reads any of `names`: a parameter expansion of
166
163
  * the name (`$x`, `${x:-…}`, `${a[x]}`), or an arithmetic expansion that
@@ -174,27 +171,6 @@ function readsAnyName(root, names, sourceCode) {
174
171
  return false;
175
172
  return someShellNode(root, (node) => readsNameHere(node, names, sourceCode));
176
173
  }
177
- /** Whether `node` itself, not its descendants, reads any of `names`. */
178
- function readsNameHere(node, names, sourceCode) {
179
- if (node.type === 'ParamExp') {
180
- if (node.excl)
181
- return true;
182
- const param = node.param?.value;
183
- if (param !== undefined && names.includes(param))
184
- return true;
185
- if (node.index !== undefined) {
186
- const indexText = sourceCode.text.slice(node.index.range[0], node.index.range[1]);
187
- if (names.some((name) => mentionsIdentifier(indexText, name)))
188
- return true;
189
- }
190
- }
191
- if (node.type === 'ArithmExp' || node.type === 'ArithmCmd') {
192
- const arithmetic = sourceCode.text.slice(node.range[0], node.range[1]);
193
- if (names.some((name) => mentionsIdentifier(arithmetic, name)))
194
- return true;
195
- }
196
- return false;
197
- }
198
174
  /**
199
175
  * Whether `node` sits inside a function body: a function definition or a bats
200
176
  * `@test` block, which bats runs as a function.
@@ -625,9 +601,9 @@ const noMaskedExitStatus = createRule({
625
601
  if (offerSuggestion && validHere && isStandalone(stmt, sourceCode)) {
626
602
  const text = sourceCode.text;
627
603
  const start = node.range[0];
628
- const lineStart = Math.max(text.lastIndexOf('\n', start - 1), text.lastIndexOf('\r', start - 1));
629
- const indent = text.slice(lineStart + 1, start);
630
- const separator = /^[ \t]*$/u.test(indent) ? lineBreakOf(text) + indent : '; ';
604
+ const lineStart = text.lastIndexOf('\n', start - 1) + 1;
605
+ const indent = text.slice(lineStart, start);
606
+ const separator = /^[ \t]*$/u.test(indent) ? shellLineBreakOf(text, start) + indent : '; ';
631
607
  const scoped = SCOPED_BUILTINS.has(builtin) && inFunction;
632
608
  suggestion = splitText(declaration, scoped, separator, functionNames, sourceCode, transparentWrappers);
633
609
  }
@@ -1,10 +1,10 @@
1
1
  import { resolveTransparentWrappers } from './resolve-transparent-wrappers.js';
2
- import { harvestCommands } from '../command-harvest/harvest-commands.js';
2
+ import { functionNames, harvestCommands } from '../command-harvest/harvest-commands.js';
3
3
  import { harvestWrapperTable } from '../command-harvest/wrapper-table.js';
4
4
  import { createRule } from './create-rule.js';
5
5
  import { getDeclaredCommands } from '../declaration-conventions/get-declared-commands.js';
6
6
  import { resolveDeclarationConvention } from './resolve-declaration-convention.js';
7
- import { SHELL_WRAPPER } from './transparent-wrappers.js';
7
+ import { BUILTIN_WRAPPER, SHELL_WRAPPER } from './transparent-wrappers.js';
8
8
  /** The registry name of this rule (`sh/no-unused-declarations` in a user's config). */
9
9
  const RULE_NAME = 'no-unused-declarations';
10
10
  /**
@@ -82,6 +82,41 @@ function resolveEffective(site, table) {
82
82
  current = [{ ...spec, names: [path] }, ...current];
83
83
  }
84
84
  }
85
+ /** Whether a resolved command can remove a function from command lookup. */
86
+ function canRemoveFunctions(site, resolution, dialect) {
87
+ const { effective, chainIndices } = resolution;
88
+ if (!effective.static)
89
+ return false;
90
+ const command = effective.text;
91
+ if (dialect === 'zsh' && command === 'unfunction')
92
+ return true;
93
+ if (command !== 'unset' && !(dialect === 'zsh' && command === 'disable'))
94
+ return false;
95
+ let flags = '';
96
+ const args = site.argv.slice((chainIndices.at(-1) ?? 0) + 1);
97
+ let index = 0;
98
+ let unknownOptions = false;
99
+ for (; index < args.length; index++) {
100
+ const word = args[index];
101
+ if (!word.static) {
102
+ unknownOptions = true;
103
+ break;
104
+ }
105
+ if (word.text === '--') {
106
+ index++;
107
+ break;
108
+ }
109
+ if (!/^-[a-z]+$/iu.test(word.text))
110
+ break;
111
+ flags += word.text.slice(1);
112
+ }
113
+ if (index === args.length)
114
+ return false;
115
+ // Bash rejects combining -v with -f, including when an expansion supplies -f.
116
+ if (command === 'unset' && dialect === 'bash' && flags.includes('v'))
117
+ return false;
118
+ return unknownOptions || flags.includes('f') || (command === 'unset' && !flags.includes('v'));
119
+ }
85
120
  /** A short-option cluster that includes `c` (`-c`, `-ec`, `-xc`): a shell's command-string flag. */
86
121
  const COMMAND_STRING_CLUSTER = /^-[A-Za-z]*c[A-Za-z]*$/u;
87
122
  /**
@@ -111,16 +146,9 @@ function passesShellCommandString(argv) {
111
146
  * With {@link SHELL_WRAPPER} followed, a script operand would be the
112
147
  * effective command and `-c` would be an embedded command, so a shell that
113
148
  * is still the effective command reads its code from standard input
114
- * (`curl x | bash`, `bash < script`, `bash -s`);
115
- * - it hands a command string to a shell named in its arguments (see
116
- * {@link passesShellCommandString}).
117
- *
118
- * `completenessWrappers` is the table to follow (see the rule's `create`).
149
+ * (`curl x | bash`, `bash < script`, `bash -s`).
119
150
  */
120
- function runsUnknownCode(site, completenessWrappers) {
121
- if (passesShellCommandString(site.argv))
122
- return true;
123
- const resolution = resolveEffective(site, completenessWrappers);
151
+ function runsUnknownCode(site, resolution) {
124
152
  const { effective, chainIndices } = resolution;
125
153
  if (!effective.static)
126
154
  return true;
@@ -141,6 +169,19 @@ function namesFor(text) {
141
169
  const base = pathBasename(text);
142
170
  return base === null ? [text] : [text, base];
143
171
  }
172
+ /** Only direct, synchronous top-level definitions give us a source-order guarantee. */
173
+ function topLevelFunctionEnds(sourceCode) {
174
+ const ends = new Map();
175
+ for (const stmt of sourceCode.ast.stmts) {
176
+ if (stmt.cmd?.type !== 'FuncDecl' || stmt.background || stmt.coprocess || stmt.disown)
177
+ continue;
178
+ for (const name of functionNames(stmt.cmd)) {
179
+ if (!ends.has(name))
180
+ ends.set(name, stmt.range[1]);
181
+ }
182
+ }
183
+ return ends;
184
+ }
144
185
  /**
145
186
  * How a report names where an out-of-script declaration lives: `path:line`
146
187
  * (or `path` when the line is unknown) for a file, the description for a
@@ -178,13 +219,17 @@ export const noUnusedDeclarations = createRule({
178
219
  }
179
220
  const { sourceCode } = context;
180
221
  const transparentWrappers = resolveTransparentWrappers(context, harvestWrapperTable(sourceCode.dialect));
181
- // The completeness check follows the harvest's table plus shells
222
+ // The completeness check follows the harvest's table plus `builtin` and shells
182
223
  // invoked as commands, so `bash -c '…'` and `sh -c '…'` resolve to an
183
224
  // embedded command (as in `no-dynamic-invocation`) instead of stopping
184
225
  // at the shell. `env -S` is already embedded in the defaults. Path
185
226
  // forms (`/bin/bash`, `/usr/bin/env`) are followed per site by
186
227
  // `resolveEffective`.
187
- const completenessWrappers = [...transparentWrappers, SHELL_WRAPPER];
228
+ const completenessWrappers = [
229
+ ...transparentWrappers,
230
+ BUILTIN_WRAPPER,
231
+ SHELL_WRAPPER,
232
+ ];
188
233
  // Bound once so the hook keeps its convention as `this`, however it is written.
189
234
  const removeDeclaration = convention.removeDeclaration?.bind(convention);
190
235
  return {
@@ -195,10 +240,30 @@ export const noUnusedDeclarations = createRule({
195
240
  return;
196
241
  }
197
242
  const sites = inventory.commands;
198
- if (sites.some((site) => runsUnknownCode(site, completenessWrappers)))
199
- return;
243
+ let mayRemoveFunctions = false;
244
+ for (const site of sites) {
245
+ if (passesShellCommandString(site.argv))
246
+ return;
247
+ const resolution = resolveEffective(site, completenessWrappers);
248
+ if (runsUnknownCode(site, resolution))
249
+ return;
250
+ // A removal in a function or a trap can happen at a later call site.
251
+ mayRemoveFunctions ||= canRemoveFunctions(site, resolution, sourceCode.dialect);
252
+ }
200
253
  const used = new Set();
201
- for (const name of harvestCommands(sourceCode, { transparentWrappers }).commands.keys()) {
254
+ const functionEnds = mayRemoveFunctions ? undefined : topLevelFunctionEnds(sourceCode);
255
+ const harvest = harvestCommands(sourceCode, {
256
+ transparentWrappers,
257
+ excludeFunction(name, site) {
258
+ const end = functionEnds?.get(name);
259
+ if (end === undefined || end > site.node.range[0])
260
+ return false;
261
+ // A nested call can run earlier than its source position suggests.
262
+ const stmt = sourceCode.getParent(site.node);
263
+ return stmt?.type === 'Stmt' && sourceCode.getParent(stmt) === sourceCode.ast;
264
+ },
265
+ });
266
+ for (const name of harvest.commands.keys()) {
202
267
  for (const each of namesFor(name))
203
268
  used.add(each);
204
269
  }