@eslint-sh/eslint-plugin 0.11.0 → 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 +1 -1
@@ -1,83 +1,552 @@
1
1
  /**
2
- * Shared reading of a shebang line's interpreter, so every rule that asks
3
- * "which shell does this file name?" gets one answer instead of re-deriving it.
4
- */
5
- /**
6
- * `env` options that consume the following word as their argument
7
- * (GNU coreutils and BSD spellings). Skipping that word keeps it from being
8
- * mistaken for the command `env` runs.
2
+ * Read the kernel's interpreter path and optional argument, then apply the GNU
3
+ * env argument grammar when the path names env. A shebang is a shell comment.
9
4
  */
5
+ import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
6
+ // The shared wrapper table covers ordinary options. The shebang reader handles
7
+ // GNU argv0 and signal options locally and requires env to execute a command.
8
+ const envWrapper = DEFAULT_TRANSPARENT_WRAPPERS.find((spec) => spec.names.includes('env'));
10
9
  const ENV_OPTIONS_WITH_ARGUMENT = new Set([
11
- '-u',
12
- '--unset',
13
- '-C',
14
- '--chdir',
15
- '-P',
10
+ ...(envWrapper?.argFlags ?? []),
11
+ '-a',
12
+ '--argv0',
13
+ '-S',
14
+ '--split-string',
15
+ ]);
16
+ const ENV_OPTIONS_WITHOUT_ARGUMENT = new Set([
17
+ ...(envWrapper?.noArgFlags?.filter((flag) => flag !== '-0' && flag !== '--null') ?? []),
18
+ '--list-signal-handling',
19
+ ]);
20
+ const ENV_SIGNAL_OPTIONS = new Set(['--default-signal', '--ignore-signal', '--block-signal']);
21
+ const ENV_LONG_OPTIONS = [
22
+ ...[...ENV_OPTIONS_WITH_ARGUMENT, ...ENV_OPTIONS_WITHOUT_ARGUMENT].filter((flag) => flag.startsWith('--')),
23
+ ...ENV_SIGNAL_OPTIONS,
24
+ // These participate in abbreviation matching even though none can run a command.
25
+ '--null',
26
+ '--help',
27
+ '--version',
28
+ ];
29
+ /** GNU getopt_long gives an exact spelling priority over unique prefixes. */
30
+ function longEnvOption(prefix) {
31
+ if (ENV_LONG_OPTIONS.includes(prefix))
32
+ return prefix;
33
+ const matches = ENV_LONG_OPTIONS.filter((flag) => flag.startsWith(prefix));
34
+ return matches.length === 1 ? matches[0] : undefined;
35
+ }
36
+ /** The interpreter names accepted by require-shebang. @internal */
37
+ export const RECOGNIZED_SHELLS = new Set([
38
+ 'bash',
39
+ 'sh',
40
+ 'dash',
41
+ 'ksh',
42
+ 'mksh',
43
+ 'zsh',
44
+ 'bats',
45
+ ]);
46
+ /** Linux signal names in numeric order, starting at signal 1. */
47
+ const SIGNAL_NAMES = ('HUP INT QUIT ILL TRAP ABRT BUS FPE KILL USR1 SEGV USR2 PIPE ALRM TERM STKFLT CHLD CONT ' +
48
+ 'STOP TSTP TTIN TTOU URG XCPU XFSZ VTALRM PROF WINCH IO PWR SYS').split(' ');
49
+ const SIGNAL_ALIASES = new Map([
50
+ ['IOT', 'ABRT'],
51
+ ['CLD', 'CHLD'],
52
+ ['POLL', 'IO'],
53
+ ]);
54
+ const SIGNALS_WITHOUT_DISPOSITION = new Set([9, 19, 32, 33]);
55
+ /** GNU operand2sig accepts both signal numbers and shell exit statuses. */
56
+ function signalNumber(operand) {
57
+ const uppercase = operand.replace(/[a-z]/gu, (char) => char.toUpperCase());
58
+ const signal = uppercase.replace(/^SIG/u, '');
59
+ if (/^[0-9]+$/u.test(signal)) {
60
+ const number = Number(signal);
61
+ if (number > 0x7fffffff)
62
+ return undefined;
63
+ const decoded = signal === uppercase ? number & (number >= 0xff ? 0xff : 0x7f) : number;
64
+ return decoded >= 1 && decoded <= 64 ? decoded : undefined;
65
+ }
66
+ const realtime = /^(RTMIN|RTMAX)(?:[ \t\n\v\f\r]*([+-]?[0-9]+))?$/u.exec(signal);
67
+ if (realtime !== null) {
68
+ const offset = Number(realtime.at(2) ?? '0');
69
+ const number = (realtime[1] === 'RTMIN' ? 34 : 64) + offset;
70
+ return number >= 34 && number <= 64 ? number : undefined;
71
+ }
72
+ const number = SIGNAL_NAMES.indexOf(SIGNAL_ALIASES.get(signal) ?? signal) + 1;
73
+ return number === 0 ? undefined : number;
74
+ }
75
+ const SPLIT_ESCAPES = new Map([
76
+ ['"', '"'],
77
+ ["'", "'"],
78
+ ['#', '#'],
79
+ ['$', '$'],
80
+ ['\\', '\\'],
81
+ ['_', ' '],
82
+ ['f', '\f'],
83
+ ['n', '\n'],
84
+ ['r', '\r'],
85
+ ['t', '\t'],
86
+ ['v', '\v'],
16
87
  ]);
17
- /** A `NAME=value` word, which `env` treats as an environment assignment. */
18
- const ENV_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/u;
88
+ /** A word made entirely of unquoted expansions can disappear when they are unset. */
89
+ function splitEnvString(text) {
90
+ const words = [];
91
+ const variable = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/uy;
92
+ let quote;
93
+ let word;
94
+ let expansions = [];
95
+ let possibleComment = false;
96
+ const finishWord = () => {
97
+ const literals = word?.join('') ?? '';
98
+ if (expansions.length > 0) {
99
+ words.push({
100
+ word: { prefix: literals.slice(0, expansions[0][0]), literals, expansions },
101
+ omit: possibleComment ? 'split' : word === undefined ? 'word' : undefined,
102
+ });
103
+ }
104
+ else if (word !== undefined)
105
+ words.push({ word: literals, omit: undefined });
106
+ word = undefined;
107
+ expansions = [];
108
+ possibleComment = false;
109
+ };
110
+ for (let index = 0; index < text.length; index++) {
111
+ const char = text[index];
112
+ const next = text[index + 1];
113
+ if (char === quote || (quote === undefined && (char === '"' || char === "'"))) {
114
+ quote = quote === undefined ? char : undefined;
115
+ word ??= [];
116
+ }
117
+ else if (char === '\\' && (quote !== "'" || next === '\\' || next === "'")) {
118
+ index++;
119
+ if (next === 'c' && quote === undefined)
120
+ break;
121
+ if (next === '_' && quote === undefined) {
122
+ finishWord();
123
+ continue;
124
+ }
125
+ const decoded = SPLIT_ESCAPES.get(next);
126
+ if (decoded === undefined)
127
+ return undefined;
128
+ (word ??= []).push(decoded);
129
+ }
130
+ else if (quote === undefined && /[ \t\n\v\f\r]/u.test(char)) {
131
+ finishWord();
132
+ }
133
+ else if (char === '#' && word === undefined) {
134
+ if (expansions.length === 0)
135
+ break;
136
+ // A set variable starts a word even when its value is empty.
137
+ possibleComment = true;
138
+ word = [char];
139
+ }
140
+ else if (char === '$' && quote !== "'") {
141
+ variable.lastIndex = index;
142
+ const expansion = variable.exec(text);
143
+ if (expansion === null)
144
+ return undefined;
145
+ expansions.push([word?.length ?? 0, expansion[1]]);
146
+ index = variable.lastIndex - 1;
147
+ }
148
+ else {
149
+ (word ??= []).push(char);
150
+ }
151
+ }
152
+ if (quote !== undefined)
153
+ return undefined;
154
+ finishWord();
155
+ return words;
156
+ }
157
+ /** Strip an option spelling that lies entirely before the first expansion. */
158
+ function attachedValue(word, start) {
159
+ if (typeof word === 'string')
160
+ return word.slice(start);
161
+ return {
162
+ prefix: word.prefix.slice(start),
163
+ literals: word.literals.slice(start),
164
+ expansions: word.expansions.map(([offset, name]) => [offset - start, name]),
165
+ };
166
+ }
19
167
  /** The final path segment of `path` (`/usr/local/bin/bash` → `bash`). */
20
168
  function basename(path) {
21
169
  return path.slice(path.lastIndexOf('/') + 1);
22
170
  }
171
+ const ENV_WORK_PER_CODE_UNIT = 64;
172
+ // Attached splits repeatedly scan a shrinking suffix. Reserve work for these
173
+ // scans and alternate readings of headers that fit in Linux's 256-byte buffer.
174
+ const ENV_KERNEL_HEADER_WORK = 16 * 256 ** 2;
175
+ const ENV_BUDGET_EXHAUSTED = new Error('GNU env shebang work budget exhausted');
23
176
  /**
24
- * The command an `env` shebang runs, given the words after `env`, or
25
- * `undefined` when there is none. Options, their arguments, and `NAME=value`
26
- * assignments are skipped; `--` ends the options, but assignments after it
27
- * still apply (GNU `env -- FOO=1 sh` runs `sh`). `-S` (split string) is transparent here because
28
- * the shebang's words are already split on whitespace, so `env -S bash -e`
29
- * runs `bash`.
177
+ * A work limit shared by all readings of one env argument. Each charge covers
178
+ * a bounded amount of work per argument node or code unit. Charge before
179
+ * scanning, copying, or looking up input-sized strings.
180
+ *
181
+ * @internal
30
182
  */
31
- function envCommand(words) {
32
- for (let index = 0; index < words.length; index++) {
33
- const word = words[index];
34
- if (word === '--') {
35
- return words.slice(index + 1).find((operand) => !ENV_ASSIGNMENT.test(operand));
36
- }
37
- // GNU env sees the whole kernel argument as an option name unless the long form uses '='.
38
- if (word === '--split-string')
183
+ export class EnvReadBudget {
184
+ remaining;
185
+ constructor(length) {
186
+ this.remaining = Math.max(ENV_WORK_PER_CODE_UNIT * length, ENV_KERNEL_HEADER_WORK);
187
+ }
188
+ charge(units) {
189
+ if (units > this.remaining)
190
+ throw ENV_BUDGET_EXHAUSTED;
191
+ this.remaining -= units;
192
+ }
193
+ }
194
+ function shellArgument(word) {
195
+ return typeof word === 'string' ? word : null;
196
+ }
197
+ /** Intern argument suffixes by value so a split can reuse its outer tail. */
198
+ class EnvArguments {
199
+ budget;
200
+ wordsByValue = new Map();
201
+ argumentsByValue = new Map();
202
+ splits = new Map();
203
+ shellSuffixes = new Map();
204
+ shellIdsByArgument = new Map();
205
+ nextShellId = 2;
206
+ constructor(budget) {
207
+ this.budget = budget;
208
+ }
209
+ prepend(word, next, absent) {
210
+ // Charge before serializing the word, including any expansion records.
211
+ let size = typeof word === 'string' ? word.length : word.prefix.length + word.literals.length;
212
+ this.budget.charge(size + 1);
213
+ if (typeof word !== 'string') {
214
+ for (const [, name] of word.expansions) {
215
+ const units = name.length + 1;
216
+ this.budget.charge(units);
217
+ size += units;
218
+ }
219
+ }
220
+ const wordKey = JSON.stringify(word);
221
+ const wordId = this.wordsByValue.get(wordKey) ?? this.wordsByValue.size + 1;
222
+ this.wordsByValue.set(wordKey, wordId);
223
+ const key = JSON.stringify([wordId, next?.id ?? 0, absent === null ? 0 : absent?.id]);
224
+ const existing = this.argumentsByValue.get(key);
225
+ if (existing !== undefined)
226
+ return existing;
227
+ const argument = { id: this.argumentsByValue.size + 1, wordId, word, size, next, absent };
228
+ this.argumentsByValue.set(key, argument);
229
+ return argument;
230
+ }
231
+ split(text, tail) {
232
+ this.budget.charge(text.length + 1);
233
+ if (!this.splits.has(text))
234
+ this.splits.set(text, splitEnvString(text));
235
+ const words = this.splits.get(text);
236
+ if (words === undefined)
39
237
  return undefined;
40
- if (word === '-S')
238
+ let args = tail;
239
+ for (let index = words.length - 1; index >= 0; index--) {
240
+ const { word, omit } = words[index];
241
+ args = this.prepend(word, args, omit === 'split' ? tail : omit === 'word' ? args : undefined);
242
+ }
243
+ return args;
244
+ }
245
+ /** Intern the shell's view of each shared suffix once, without flattening it. */
246
+ shellSuffixId(tail) {
247
+ const pending = [];
248
+ let id = 0;
249
+ for (let arg = tail; arg !== null; arg = arg.next) {
250
+ this.budget.charge(1);
251
+ if (arg.absent !== undefined) {
252
+ id = 1; // The remaining argv can change length.
253
+ break;
254
+ }
255
+ const cached = this.shellSuffixes.get(arg);
256
+ if (cached !== undefined) {
257
+ id = cached;
258
+ break;
259
+ }
260
+ pending.push(arg);
261
+ }
262
+ for (let index = pending.length - 1; index >= 0; index--) {
263
+ const arg = pending[index];
264
+ this.budget.charge(arg.size + 1);
265
+ const value = shellArgument(arg.word);
266
+ let idsByTail = this.shellIdsByArgument.get(value);
267
+ if (idsByTail === undefined) {
268
+ idsByTail = new Map();
269
+ this.shellIdsByArgument.set(value, idsByTail);
270
+ }
271
+ const suffix = id;
272
+ id = idsByTail.get(suffix) ?? this.nextShellId++;
273
+ idsByTail.set(suffix, id);
274
+ this.shellSuffixes.set(arg, id);
275
+ }
276
+ return id;
277
+ }
278
+ }
279
+ function readEnvOption(args, initial, argumentsByValue) {
280
+ const { word, next } = args;
281
+ const prefix = typeof word === 'string' ? word : word.prefix;
282
+ const state = { ...initial };
283
+ const long = prefix.startsWith('--');
284
+ const equals = long ? prefix.indexOf('=') : -1;
285
+ const longValue = equals === -1 ? undefined : attachedValue(word, equals + 1);
286
+ let flags;
287
+ if (long) {
288
+ if (equals === -1 && typeof word !== 'string')
289
+ return undefined;
290
+ const option = longEnvOption(equals === -1 ? prefix : prefix.slice(0, equals));
291
+ if (option === undefined)
292
+ return undefined;
293
+ if (ENV_SIGNAL_OPTIONS.has(option)) {
294
+ if (typeof longValue === 'object')
295
+ return undefined;
296
+ if (longValue === undefined && option !== '--block-signal') {
297
+ // A bare disposition option replaces all preceding dispositions and ignores errors.
298
+ state.invalidDisposition = false;
299
+ }
300
+ for (const entry of longValue?.split(',') ?? []) {
301
+ if (entry === '')
302
+ continue;
303
+ const signal = signalNumber(entry);
304
+ if (signal === undefined)
305
+ return undefined;
306
+ if (option === '--block-signal') {
307
+ if (signal === 32 || signal === 33)
308
+ return undefined;
309
+ }
310
+ else {
311
+ state.invalidDisposition ||= SIGNALS_WITHOUT_DISPOSITION.has(signal);
312
+ }
313
+ }
314
+ return { args: next, state, mode: 'options' };
315
+ }
316
+ flags = [option];
317
+ }
318
+ else {
319
+ flags = Array.from(prefix.slice(1), (flag) => '-' + flag);
320
+ }
321
+ for (let position = 0; position < flags.length; position++) {
322
+ const flag = flags[position];
323
+ if (ENV_OPTIONS_WITHOUT_ARGUMENT.has(flag)) {
324
+ if (longValue !== undefined)
325
+ return undefined;
326
+ if (flag === '-i' || flag === '--ignore-environment') {
327
+ state.ignoreEnvironment = true;
328
+ state.invalidUnset = false;
329
+ }
41
330
  continue;
42
- if (word.startsWith('--split-string=')) {
43
- return word.slice('--split-string='.length) || words[index + 1];
44
331
  }
45
- if (word.startsWith('-S')) {
46
- return word.slice('-S'.length);
332
+ if (!ENV_OPTIONS_WITH_ARGUMENT.has(flag))
333
+ return undefined;
334
+ const attached = long ? longValue : attachedValue(word, position + 2);
335
+ if (attached === undefined || (!long && attached === '')) {
336
+ return { args: next, state, mode: flag };
47
337
  }
48
- if (ENV_OPTIONS_WITH_ARGUMENT.has(word)) {
49
- index++;
338
+ // An empty short-option suffix leaves the next word in the argument slot.
339
+ const absent = !long && typeof attached === 'object' && attached.literals === '' ? next : undefined;
340
+ return { args: argumentsByValue.prepend(attached, next, absent), state, mode: flag };
341
+ }
342
+ return typeof word === 'string' ? { args: next, state, mode: 'options' } : undefined;
343
+ }
344
+ function readEnvOperand(args, state, first) {
345
+ const { word, next } = args;
346
+ if (first && word === '-') {
347
+ return {
348
+ args: next,
349
+ state: { ...state, ignoreEnvironment: true, invalidUnset: false },
350
+ mode: 'assignments',
351
+ };
352
+ }
353
+ if (state.directory === '' ||
354
+ state.directory === null ||
355
+ state.invalidDisposition ||
356
+ state.invalidUnset) {
357
+ return undefined;
358
+ }
359
+ // Any literal '=' guarantees an assignment once getopt has stopped.
360
+ if ((typeof word === 'string' ? word : word.literals).includes('=')) {
361
+ return { args: next, state, mode: 'assignments' };
362
+ }
363
+ if (typeof word !== 'string')
364
+ return undefined;
365
+ return {
366
+ executable: word,
367
+ directory: state.directory,
368
+ argv0Overridden: state.argv0Overridden,
369
+ args: next,
370
+ };
371
+ }
372
+ function shellArguments(tail, budget) {
373
+ const shellArgs = [];
374
+ for (let arg = tail; arg !== null; arg = arg.next) {
375
+ budget.charge(arg.size + 1);
376
+ if (arg.absent !== undefined) {
377
+ shellArgs.push(null);
378
+ break;
379
+ }
380
+ shellArgs.push(shellArgument(arg.word));
381
+ }
382
+ return shellArgs;
383
+ }
384
+ function readEnvArgument(args, state, flag, argumentsByValue) {
385
+ const { word, next } = args;
386
+ if (flag === '-S' || flag === '--split-string') {
387
+ // GNU restarts getopt with the split value followed by its unused argv.
388
+ if (typeof word !== 'string')
389
+ return undefined;
390
+ const split = argumentsByValue.split(word, next);
391
+ return split === undefined ? undefined : { args: split, state, mode: 'options' };
392
+ }
393
+ const updated = { ...state };
394
+ if (flag === '-a' || flag === '--argv0')
395
+ updated.argv0Overridden = true;
396
+ if (flag === '-C' || flag === '--chdir') {
397
+ const literals = typeof word === 'string' ? word : word.literals;
398
+ updated.directory = word === '.' ? 0 : literals === '' ? '' : args.wordId;
399
+ }
400
+ if (!state.ignoreEnvironment && (flag === '-u' || flag === '--unset')) {
401
+ // An expansion can supply '=' even when the name has literal text.
402
+ updated.invalidUnset ||= typeof word !== 'string' || word === '' || word.includes('=');
403
+ }
404
+ return { args: next, state: updated, mode: 'options' };
405
+ }
406
+ function readEnvWord(args, { state, mode }, argumentsByValue) {
407
+ if (mode === 'options') {
408
+ const { word } = args;
409
+ if (word === '--')
410
+ return { args: args.next, state, mode: 'operands' };
411
+ const prefix = typeof word === 'string' ? word : word.prefix;
412
+ if (typeof word !== 'string' && prefix === '')
413
+ return undefined;
414
+ if (prefix.startsWith('-') && word !== '-')
415
+ return readEnvOption(args, state, argumentsByValue);
416
+ return readEnvOperand(args, state, true);
417
+ }
418
+ if (mode === 'operands' || mode === 'assignments') {
419
+ return readEnvOperand(args, state, mode === 'operands');
420
+ }
421
+ return readEnvArgument(args, state, mode, argumentsByValue);
422
+ }
423
+ function envCommand(argument) {
424
+ const budget = new EnvReadBudget(argument.length);
425
+ try {
426
+ return readEnvCommand(argument, budget);
427
+ }
428
+ catch (error) {
429
+ if (error === ENV_BUDGET_EXHAUSTED)
430
+ return undefined;
431
+ throw error;
432
+ }
433
+ }
434
+ function readEnvCommand(argument, budget) {
435
+ const initial = {
436
+ ignoreEnvironment: false,
437
+ invalidUnset: false,
438
+ invalidDisposition: false,
439
+ argv0Overridden: false,
440
+ directory: 0,
441
+ };
442
+ const argumentsByValue = new EnvArguments(budget);
443
+ const pending = [
444
+ { args: argumentsByValue.prepend(argument, null), state: initial, mode: 'options' },
445
+ ];
446
+ // Only the last -C takes effect. Merge incoming directories at the same
447
+ // cursor so the suffix can erase their differences with an overwrite.
448
+ const seen = new Map();
449
+ let expected;
450
+ let argsAgree = true;
451
+ let argv0Overridden = false;
452
+ let chdirRequested = false;
453
+ for (let reading = pending.pop(); reading !== undefined; reading = pending.pop()) {
454
+ budget.charge(1);
455
+ const { args, mode } = reading;
456
+ let { state } = reading;
457
+ if (args === null)
458
+ return undefined;
459
+ // Record use of -C independently of the effective directory. A later
460
+ // override or a merged reading can erase the directory's earlier value.
461
+ chdirRequested ||= mode === '-C' || mode === '--chdir';
462
+ const key = JSON.stringify([
463
+ args.id,
464
+ mode,
465
+ state.ignoreEnvironment,
466
+ state.invalidUnset,
467
+ state.invalidDisposition,
468
+ state.argv0Overridden,
469
+ ]);
470
+ const previousDirectory = seen.get(key);
471
+ if (previousDirectory === state.directory || previousDirectory === null)
472
+ continue;
473
+ if (previousDirectory !== undefined)
474
+ state = { ...state, directory: null };
475
+ seen.set(key, state.directory);
476
+ // Reading a word can scan its option spelling, split a signal list, or
477
+ // copy an attached expansion. Charge its full size before those steps.
478
+ budget.charge(args.size + 1);
479
+ if (args.absent !== undefined)
480
+ pending.push({ args: args.absent, mode, state });
481
+ const result = readEnvWord(args, { args, mode, state }, argumentsByValue);
482
+ if (result === undefined)
483
+ return undefined;
484
+ if ('mode' in result) {
485
+ pending.push(result);
50
486
  continue;
51
487
  }
52
- if (word.startsWith('-') || ENV_ASSIGNMENT.test(word)) {
488
+ argv0Overridden ||= result.argv0Overridden;
489
+ if (expected === undefined) {
490
+ expected = result;
53
491
  continue;
54
492
  }
55
- return word;
493
+ if (result.executable !== expected.executable || result.directory !== expected.directory) {
494
+ return undefined;
495
+ }
496
+ if (argsAgree && expected.args !== result.args) {
497
+ argsAgree =
498
+ argumentsByValue.shellSuffixId(expected.args) ===
499
+ argumentsByValue.shellSuffixId(result.args);
500
+ }
501
+ }
502
+ if (expected === undefined)
503
+ return undefined;
504
+ return {
505
+ shell: basename(expected.executable),
506
+ ...(chdirRequested ? { chdirRequested: true } : {}),
507
+ ...(argv0Overridden ? { argv0Overridden: true } : {}),
508
+ // Startup credit needs the whole argument list. Once readings disagree,
509
+ // later readings cannot recover it.
510
+ args: argsAgree ? shellArguments(expected.args, budget) : [null],
511
+ };
512
+ }
513
+ /** Apply the kernel's LF, NUL, and blank handling to the physical header. @internal */
514
+ export function kernelShebangLine(text) {
515
+ for (let end = 0; end < text.length; end++) {
516
+ // A NUL ends the argument without trimming preceding spaces or tabs.
517
+ if (text[end] === '\x00')
518
+ return text.slice(0, end);
519
+ if (text[end] !== '\n')
520
+ continue;
521
+ while (end > 0 && (text[end - 1] === ' ' || text[end - 1] === '\t'))
522
+ end--;
523
+ return text.slice(0, end);
56
524
  }
57
- return undefined;
525
+ return text;
58
526
  }
59
527
  /**
60
- * The shell basename a shebang's interpreter part (everything after `#!`)
61
- * runs, or `undefined` when it names no usable interpreter: either an absolute
62
- * path (`/usr/local/bin/bash` → `bash`), or an absolute path to `env` whose
63
- * command is the shell (`/usr/bin/env bash`, `/usr/bin/env -S bash -e` →
64
- * `bash`). A relative interpreter (`#!bash`) yields `undefined`: the kernel
65
- * would resolve it against the caller's working directory, not `PATH`.
66
- *
67
- * Which names count as a shell, and whether one agrees with the configured
68
- * dialect, are the callers' questions; this only answers "what runs".
528
+ * Read the interpreter basename and its initial arguments from the text
529
+ * after `#!`. An absolute path names the interpreter directly or, for `env`,
530
+ * through its command operand. A relative path depends on the caller's
531
+ * working directory.
69
532
  *
70
533
  * @internal
71
534
  */
72
- export function shebangShell(interpreterSpec) {
73
- const [interpreter, ...args] = interpreterSpec.trim().split(/\s+/u);
74
- if (!interpreter.startsWith('/')) {
535
+ export function readShebangInvocation(interpreterSpec) {
536
+ const match = /^[ \t]*(\/[^ \t]+)(?:[ \t]+(.*))?/su.exec(kernelShebangLine(interpreterSpec));
537
+ if (match === null) {
75
538
  return undefined;
76
539
  }
540
+ const interpreter = match[1];
541
+ const argument = match.at(2);
77
542
  const name = basename(interpreter);
78
543
  if (name !== 'env') {
79
- return name;
544
+ return { shell: name, args: argument === undefined ? [] : [argument] };
80
545
  }
81
- const command = envCommand(args);
82
- return command === undefined ? undefined : basename(command);
546
+ // Start with the single argument the kernel supplies before the script path.
547
+ return argument === undefined ? undefined : envCommand(argument);
548
+ }
549
+ /** The interpreter basename, independent of its arguments. @internal */
550
+ export function shebangShell(interpreterSpec) {
551
+ return readShebangInvocation(interpreterSpec)?.shell;
83
552
  }
@@ -45,12 +45,12 @@ export const shebangMatchesDialect = createRule({
45
45
  const { sourceCode } = context;
46
46
  return {
47
47
  File() {
48
+ const text = sourceCode.text.startsWith(BOM) ? sourceCode.text.slice(1) : sourceCode.text;
49
+ if (!text.startsWith('#!'))
50
+ return;
48
51
  const firstLine = sourceCode.lines[0] ?? '';
49
52
  const shebangLine = firstLine.startsWith(BOM) ? firstLine.slice(1) : firstLine;
50
- if (!shebangLine.startsWith('#!')) {
51
- return;
52
- }
53
- const messageId = mismatchFor(shebangShell(shebangLine.slice('#!'.length)), sourceCode.dialect);
53
+ const messageId = mismatchFor(shebangShell(text.slice('#!'.length)), sourceCode.dialect);
54
54
  if (messageId === undefined) {
55
55
  return;
56
56
  }
@@ -0,0 +1,12 @@
1
+ import type { ShellNode } from '../language/syntax-view.js';
2
+ import type { ShellSourceCode } from '../language/shell-source-code.js';
3
+ /**
4
+ * Whether `text` mentions `name` as a whole identifier.
5
+ * @internal
6
+ */
7
+ export declare function mentionsIdentifier(text: string, name: string): boolean;
8
+ /**
9
+ * Whether evaluating a single syntax node can read any of the given names.
10
+ * @internal
11
+ */
12
+ export declare function readsNameHere(node: ShellNode, names: readonly string[], sourceCode: ShellSourceCode): boolean;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Whether `text` mentions `name` as a whole identifier.
3
+ * @internal
4
+ */
5
+ export function mentionsIdentifier(text, name) {
6
+ return new RegExp(`(?<![A-Za-z0-9_])${name}(?![A-Za-z0-9_])`, 'u').test(text);
7
+ }
8
+ /**
9
+ * Whether evaluating a single syntax node can read any of the given names.
10
+ * @internal
11
+ */
12
+ export function readsNameHere(node, names, sourceCode) {
13
+ if (node.type === 'ParamExp') {
14
+ if (node.excl)
15
+ return true;
16
+ const param = node.param?.value;
17
+ if (param !== undefined && names.includes(param))
18
+ return true;
19
+ if (node.index !== undefined) {
20
+ const indexText = sourceCode.text.slice(node.index.range[0], node.index.range[1]);
21
+ if (names.some((name) => mentionsIdentifier(indexText, name)))
22
+ return true;
23
+ }
24
+ }
25
+ if (node.type === 'ArithmExp' || node.type === 'ArithmCmd') {
26
+ const arithmetic = sourceCode.text.slice(node.range[0], node.range[1]);
27
+ if (names.some((name) => mentionsIdentifier(arithmetic, name)))
28
+ return true;
29
+ }
30
+ return false;
31
+ }