Repository navigation
Expand file tree
/
Copy pathscan.ts
More file actions
2585 lines (2516 loc) · 102 KB
/
Copy pathscan.ts
File metadata and controls
2585 lines (2516 loc) · 102 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
export * as ShellScan from "./scan.js"
export type OpaqueReason =
| "command-substitution"
| "compound-command"
| "dynamic-command-name"
| "dynamic-execution"
| "heredoc"
| "invalid-redirect"
| "invalid-structure"
| "unsupported-escape"
| "unterminated-escape"
| "unterminated-quote"
type Command = {
resource: string
words: string[]
rawWords: string[]
// Exclusive raw-token ends relative to resource, for source-shaped permission prefixes.
wordEnds?: number[]
statementHead?: true
declaration?: true
// Words before the first redirect when redirects appear between arguments.
redirectWordCount?: number
// Exclusive prefix end relative to resource for commandless or group redirects.
redirectPrefixEnd?: number
}
// Opaque describes a parsing limitation, not a permission decision.
export type Result = { kind: "scanned"; commands: Command[] } | { kind: "opaque"; reason: OpaqueReason }
const BASH_REDIRECTS = ["&>>", "&>", "<<<", "<<-", "<<", "<>", "<&", ">&", ">|", ">>", ">", "<"]
const BASH_LIST_OPERATORS = ["&&", "||", "|&"]
const ZSH_LIST_OPERATORS = ["&&", "||", "|&", "&!", "&|"]
const BASH_CASE_OPERATORS = [";;&", ";;", ";&", ";|", ...BASH_LIST_OPERATORS]
const ZSH_CASE_OPERATORS = [";;&", ";;", ";&", ";|", ...ZSH_LIST_OPERATORS]
// Builtins that bind their operands to variables or evaluate them as variable names.
const BASH_BINDING_BUILTINS = new Set([
"declare",
"typeset",
"local",
"export",
"readonly",
"private",
"unset",
"read",
"getln",
"vared",
"getopts",
"mapfile",
"readarray",
"compgen",
"zparseopts",
"zregexparse",
"zformat",
"zstyle",
"zstat",
"stat",
])
const BASH_ARITHMETIC_COMPARISONS = new Set(["-eq", "-ne", "-lt", "-le", "-gt", "-ge"])
const BASH_EXPANSION_RE = /\$(?:\\.|\\\n)*[({]|`/
const BASH_ESCAPE_RE = /\\(?:x[\da-fA-F]{1,2}|[0-7]{1,3}|u[\da-fA-F]{1,4}|U[\da-fA-F]{1,8})/
const BASH_ASSIGNMENT_DECLARATIONS = new Set(["declare", "typeset", "export", "readonly", "local"])
const BASH_DECLARATIONS = new Set([...BASH_ASSIGNMENT_DECLARATIONS, "unset", "unsetenv"])
const BASH_PRECOMMANDS = new Set(["builtin", "command", "time", "coproc", "!"])
const ZSH_PRECOMMANDS = new Set(["noglob", "nocorrect", "exec", "-"])
const ZSH_ARITHMETIC_BUILTINS = new Set([
"integer",
"float",
"exit",
"return",
"shift",
"break",
"continue",
"bye",
"logout",
])
const BASH_NON_FUNCTION_KEYWORDS = new Set([
"if",
"for",
"select",
"case",
"then",
"elif",
"else",
"fi",
"do",
"done",
"in",
"esac",
])
// Characters that can begin a quoting or expansion unit.
const BASH_UNIT_STARTS = "\\$'\"`<>"
const MAX_INPUT_LENGTH = 64 * 1024
const MAX_SUBSTITUTION_DEPTH = 32
const TOKEN_RE = /[A-Za-z_][A-Za-z0-9_]*(?=(?:\\\n)*(?:[ \t\n;|&()<>]|$))/y
const BRACE_CLOSE_AHEAD_RE = /(?:\\\n)*(?:[ \t\n;&|()<>]|$)/y
const SPACE_CONTINUATION_AHEAD_RE = /(?:\\\n)*[ \t\n]/y
const NEGATION_AHEAD_RE = /(?:\\\n)*[ \t\n(]/y
// Ahead of a coproc or time prefix: optional negations, then a compound command.
const COMPOUND_AHEAD = String.raw`(?=(?:!(?:[ \t]|\\\n)*)*(?:[{(]|\[\[(?:\\\n)*[ \t\n]|(?:if|while|until|for|select|case|repeat)\b))`
const COPROC_AHEAD_RE = new RegExp(
String.raw`coproc(?:[ \t]|\\\n)+(?:--(?:[ \t]|\\\n)+)?(?:[A-Za-z_][A-Za-z0-9_]*(?:[ \t]|\\\n)+)?` + COMPOUND_AHEAD,
"y",
)
const TIME_AHEAD_RE = new RegExp(
String.raw`time(?:[ \t]|\\\n)+(?:-p(?:[ \t]|\\\n)+)?(?:--(?:[ \t]|\\\n)+)?` + COMPOUND_AHEAD,
"y",
)
// [function] name [()] then blanks, continuations, and comments before the body.
const FUNCTION_HEAD_RE =
/(function[ \t](?:[ \t]|\\\n)*)?([A-Za-z_][\w.:+@%-]*)?(?:[ \t]|\\\n)*(\([ \t]*\))?((?:[ \t\n]|\\\n|#[^\n]*\n)*)/y
const FUNCTION_BODY_RE =
/[{(]|\[\[(?=(?:\\\n)*[ \t\n])|(?:if|while|until|for|select|case|repeat)(?=(?:\\\n)*(?:[ \t\n(]|$))/y
const DO_AHEAD_RE = /(?:[ \t\n;]|\\\n|#[^\n]*(?:\n|$))*(?:do(?=(?:\\\n)*(?:[ \t\n;{(]|$))|\{(?=(?:\\\n)*[ \t\n]))/y
const NOFORK_OPEN_RE = /\$\{(?:\\\n)*(?:[ \t\n]|\|)/y
// Zsh flags that neither evaluate nor glob a value; s and j take an argument between repeated delimiters.
const ZSH_SAFE_FLAGS_RE = /\$\{\((?:[@AaBbCcDEfFikLMmNnOopPqStUuVvWwXZz0-]|q[+]|[js]([^({[<\\])(?:(?!\1)[^)])*\1)*\)/y
const ZSH_QUOTED_FLAG_ARG_RE = /[js]([^({[<\\])(?:(?!\1)[^)])*\1/g
const ZSH_GLOB_MODIFIER_RE = /(?:[\^=~#+]|\\\n)*~/y
// Trailing Zsh glob qualifiers without code execution (e, +cmd), delimiters (f, u, g, P), modifiers (:), or math expressions.
const ZSH_GLOB_QUALIFIER_RE =
/\((?:[/F.@=*rwxAIERWsStUG^MTNDn-]|[oO][nLlamcdN]|[amc][Mwhmsd]?[-+]?\d+|L[kKmMpPgGtT]?[-+]?\d+|[lY][-+]?\d+|\[[-+]?\d+(?:,[-+]?\d+)?\]|,)+\)(?=(?:\\\n)*(?:[ \t\n;&|<>)]|$))/y
const ZSH_SUBSCRIPT_RE = /\$(?:[\^=+~#]|\\\n)*(?:[A-Za-z_](?:[A-Za-z0-9_]|\\\n)*|[@*#?$!0-9-])(?:\\\n)*\[/y
const LINE_CONTINUATION_RE = /(?:\\\n)*/y
const PARAMETER_PREFIX_RE = /(?:\\\n)*(?:\([^)]*\))?(?:[!#^=+~]|\\\n)*/y
const PARAMETER_NAME_RE = /(?:[A-Za-z_](?:[A-Za-z0-9_]|\\\n)*|\d(?:\d|\\\n)*|[@*#?$!-])(?:\\\n)*/y
const PARAMETER_PROMPT_RE = /@(?:\\\n)*[EP](?:\\\n)*\}/y
const BASH_ANSI_ESCAPES: Record<string, string> = {
a: "\x07",
b: "\b",
e: "\x1b",
E: "\x1b",
f: "\f",
n: "\n",
r: "\r",
t: "\t",
v: "\v",
"\\": "\\",
"'": "'",
'"': '"',
"?": "?",
}
type Opaque = { kind: "opaque"; reason: OpaqueReason }
type BashResult = { kind: "scanned"; commands: Command[]; end: number } | Opaque
// Shared across one scan: the work budget, the shell dialect, and whether a bound expansion reaches a variable sink.
type BashContext = {
remaining: number
dialect: Dialect
boundDollar?: boolean
boundOpen?: boolean
boundBracket?: boolean
sinkBracket?: boolean
variableSink?: boolean
evalSink?: boolean
}
type BashHeredoc = {
delimiter: string
dashDelimiter?: string
quoted: boolean
tabs: boolean
binding?: boolean
owned?: true
command?: Command
start?: number
}
type BashState = {
input: string
context: BashContext
commands: Command[]
nestedCommands: Command[]
words: string[]
rawWords: string[]
// Pending heredocs, shared with nested groups: a body starts after the next newline token at any nesting.
heredocs: BashHeredoc[]
structures: Array<{
kind: "if" | "while" | "until" | "for" | "case" | "repeat"
phase: "header" | "condition" | "pattern" | "body" | "do"
count: number
sawElse?: boolean
sawIn?: boolean
patternStarted?: boolean
parenthesized?: boolean
}>
word: string
literal: string
output: string
wordStarted: boolean
wordStart: number
wordEnd: number
commandStart: number | undefined
redirectWordCount: number | undefined
redirectPrefixEnd: number | undefined
// Posix shells such as Dash read `&>` as `&` and `>`, so later words would start another command there.
ampersandRedirectWords: number | undefined
commandWordIndex: number
assignmentWord: boolean
assignmentHeadUnsafe: boolean
invalid: OpaqueReason | undefined
redirectTarget: boolean
dupRedirect: boolean
hereString: boolean
hasRedirect: boolean
hasFileRedirect: boolean
compoundEnd: boolean
// A list operator (&&, ||, |, |&) still awaits its right-hand command.
dangling: boolean
// Receives each word's literal text when the list is a command substitution, whose output it stands in for.
outer: BashText | undefined
}
// A word's cooked text, the literal text it decodes to apart from its expansions, and the literal text of its
// command substitutions' words, which stands in for their output.
type BashText = { word: string; literal: string; output: string }
// Arithmetic text, a builtin operand that names or binds a variable now, or a value bound for later.
type BashEvaluation = "arithmetic" | "binding" | "deferred"
// Bash and Zsh name those shells. Posix covers sh, dash, and any other shell, and stays sound for Bash, Zsh, and
// Dash alike, so it is the default.
export type Dialect = "bash" | "zsh" | "posix"
export function scan(input: string, dialect: Dialect = "posix"): Result {
if (input.length > MAX_INPUT_LENGTH) return { kind: "opaque", reason: "invalid-structure" }
const context: BashContext = { remaining: MAX_INPUT_LENGTH * MAX_SUBSTITUTION_DEPTH, dialect }
const result = scanBash(input, 0, 0, context)
if (result.kind === "opaque") return result
if (
context.boundDollar &&
context.boundOpen &&
(context.evalSink || ((context.boundBracket || context.sinkBracket) && context.variableSink))
)
return { kind: "opaque", reason: "dynamic-execution" }
return { kind: "scanned", commands: result.commands }
}
function bashStatement(state: BashState) {
const structure = state.structures.at(-1)
if (structure) structure.count++
}
function bashInHeader(state: BashState) {
const phase = state.structures.at(-1)?.phase
return phase === "header" || phase === "pattern" || phase === "do"
}
function atCommandStart(state: BashState) {
return !state.words.length && !state.hasRedirect && !state.compoundEnd && !bashInHeader(state)
}
function pending(state: BashState) {
return state.wordStarted || state.words.length > 0 || state.hasRedirect || state.compoundEnd
}
// Ends the current list; false when an operator still awaits its command.
function endBashList(state: BashState) {
if (pending(state)) finishBashCommand(state, false, true)
return !state.dangling
}
function closeBashList(state: BashState, end: number): BashResult {
if (!endBashList(state)) return { kind: "opaque", reason: "invalid-structure" }
if (state.invalid) return { kind: "opaque", reason: state.invalid }
if (state.structures.length) return { kind: "opaque", reason: "compound-command" }
return { kind: "scanned", commands: state.commands, end }
}
function finishBashWord(state: BashState) {
if (!state.wordStarted) return
if (/PS4/.test(state.word)) state.context.evalSink = true
const evaluation = bashWordEvaluation(state)
if (
state.context.dialect !== "bash" &&
(/(?:READ)?NULLCMD/.test(state.word) ||
((state.assignmentWord || evaluation === "binding") &&
/^(?:-[A-Za-z]*v)?(?:(?:dis_)?(?:functions|[gs]?aliases)|options|commands)(?:\+?=|\[|$)/.test(state.word)))
)
state.invalid ??= "dynamic-execution"
if (evaluation && bashEvaluatesExpansion(state, evaluation, state.context)) state.invalid ??= "dynamic-execution"
if (state.word !== state.literal && state.commandWordIndex >= 0) {
const builtin = state.words[bashBuiltinIndex(state)]
if (builtin === "declare" || builtin === "typeset" || builtin === "local") state.context.evalSink = true
}
if (state.outer) state.outer.output += ` ${state.literal} ${state.output}`
const structure = state.structures.at(-1)
const repeatHeader = structure?.kind === "repeat" && structure.phase === "header"
if (!state.redirectTarget && repeatHeader) structure.phase = "do"
if (!state.redirectTarget && !repeatHeader) {
if (!state.assignmentWord && state.commandWordIndex < 0) state.commandWordIndex = state.words.length
state.commandStart ??= state.wordStart
state.words.push(state.word)
// Unquoted trailing continuations are ignored syntax, not part of the raw token.
state.rawWords.push(state.input.slice(state.wordStart, state.wordEnd))
}
if (state.redirectTarget) {
if (!state.dupRedirect || !/^(?:\d+-?|-)$/.test(state.input.slice(state.wordStart, state.wordEnd)))
state.hasFileRedirect = true
state.redirectPrefixEnd ??= state.wordEnd
}
state.redirectTarget = false
state.dupRedirect = false
state.hereString = false
state.word = ""
state.literal = ""
state.output = ""
state.wordStarted = false
state.assignmentWord = false
state.assignmentHeadUnsafe = false
}
// How the shell evaluates the current word's literal text: as arithmetic, or as a value it binds to a variable
// that a later $((name)) may evaluate.
function bashWordEvaluation(state: BashState): BashEvaluation | undefined {
if (state.redirectTarget) return state.hereString ? "deferred" : undefined
const structure = state.structures.at(-1)
if (structure?.kind === "repeat" && structure.phase === "header") return "arithmetic"
if (structure?.kind === "for" && structure.phase === "header" && structure.sawIn) return "deferred"
if (state.commandWordIndex < 0) return state.assignmentWord ? "deferred" : undefined
const name = bashBuiltinIndex(state)
const command = state.words[name]
if (command === undefined) return undefined
if (command === "let" || (state.context.dialect !== "bash" && ZSH_ARITHMETIC_BUILTINS.has(command)))
return "arithmetic"
if (command === "set")
return state.words.slice(name + 1).some((word) => /^[-+][A-Za-z0-9]*A/.test(word)) ? "binding" : "deferred"
if (BASH_BINDING_BUILTINS.has(command)) {
const options = state.words.slice(name + 1)
if (options.some((word) => word.startsWith("-") && /[EFin]/.test(word))) return "arithmetic"
// A plain `name=value` declaration without options binds a scalar unless Bash re-parses an existing array.
if (
state.assignmentWord &&
BASH_ASSIGNMENT_DECLARATIONS.has(command) &&
options.every((word) => !word.startsWith("-")) &&
(command === "export" ||
command === "readonly" ||
state.context.dialect === "zsh" ||
!/\+?=(?:\(|[$`])/.test(state.word))
)
return "deferred"
return "binding"
}
if (command === "printf" || command === "print") {
const options = [...state.words.slice(name + 1), state.word]
const flag = command === "print" ? /^-[A-Za-z]*v/ : /^-v/
return options.some((word) => flag.test(word)) ? "binding" : undefined
}
if (command === "wait")
return /^-[nf]*p/.test(state.word) || /^-[nf]*p$/.test(state.words.at(-1) ?? "") ? "binding" : undefined
if (command === "test" || command === "[") {
if (state.words.at(-1) === "-v") return "binding"
if (state.context.dialect !== "bash" && state.words.at(-1) === "-t") return "arithmetic"
}
return undefined
}
// Index of the word naming the builtin that runs, skipping precommand wrappers and their options.
function bashBuiltinIndex(state: BashState) {
let name = state.commandWordIndex
while (
BASH_PRECOMMANDS.has(state.words[name] ?? "") ||
(state.context.dialect !== "bash" && ZSH_PRECOMMANDS.has(state.words[name] ?? ""))
) {
const precommand = state.words[name++]
while (precommand !== "-" && state.words[name]?.startsWith("-")) {
if (precommand === "exec" && /^-[cl]*a$/.test(state.words[name])) name++
name++
}
}
return name
}
function finishBashCommand(state: BashState, boundary = false, newline = false) {
finishBashWord(state)
if (state.redirectTarget) state.invalid ??= "invalid-redirect"
state.redirectTarget = false
if (state.compoundEnd && state.words.length > 0) state.invalid ??= "invalid-structure"
const name = state.commandWordIndex
const inHeader = bashInHeader(state)
if (name >= 0 && !state.words[name]) state.invalid ??= "invalid-structure"
let owner: Command | undefined
if (name >= 0 && !inHeader) {
const resource = state.input.slice(state.commandStart, state.wordEnd).replace(/^[ \t\n]+|[ \t\n]+$/g, "")
const command: Command = {
resource,
words: state.words.slice(name),
rawWords: state.rawWords.slice(name),
...(name === 0 &&
!state.hasRedirect &&
BASH_DECLARATIONS.has(state.rawWords[0]) &&
resource.startsWith(state.rawWords[0])
? { declaration: true as const }
: {}),
...(state.redirectWordCount !== undefined && state.redirectWordCount < state.words.length
? { redirectWordCount: state.redirectWordCount - name }
: {}),
}
state.commands.push(command)
const builtin = bashBuiltinIndex(state)
const builtinName = state.words[builtin]
const builtinArgs = state.words.slice(builtin + 1)
if (builtinName === "eval") state.context.evalSink = true
if (builtinName === "set" && builtinArgs.some((word) => /^-[A-Za-z0-9]*k/.test(word) || word === "keyword"))
state.invalid ??= "dynamic-execution"
// Dash expands an alias defined earlier in the same script, which can name any command.
if (builtinName === "alias" && builtinArgs.some((word) => word.includes("="))) state.invalid ??= "dynamic-execution"
// Zsh options such as globsubst, kshglob, and promptsubst enable evaluation on expansions and print -P.
if (
state.context.dialect !== "bash" &&
(builtinName === "emulate" ||
((builtinName === "setopt" ||
builtinName === "unsetopt" ||
(builtinName === "set" && builtinArgs.some((word) => /^[-+][A-Za-z0-9]*o/.test(word)))) &&
builtinArgs.some(
(word) =>
/^-[A-Za-z0-9]*m/.test(word) ||
/^(?:no)?(?:globsubst|kshglob|promptsubst|promptvars|aliases)$/.test(
word
.replace(/^[-+][A-Za-z0-9]*?o/i, "")
.toLowerCase()
.replace(/[_-]/g, ""),
),
)))
)
state.invalid ??= "dynamic-execution"
// Bash compgen -C and -F execute their argument immediately to generate completions.
if (
state.context.dialect !== "zsh" &&
builtinName === "compgen" &&
builtinArgs.some((word) => word.startsWith("-") && /[CF]/.test(word))
)
state.invalid ??= "dynamic-execution"
if (BASH_BINDING_BUILTINS.has(builtinName ?? "")) {
for (const heredoc of state.heredocs) heredoc.binding ??= true
}
owner = command
} else if (
name < 0 &&
!inHeader &&
state.commandStart !== undefined &&
(state.hasFileRedirect || (state.hasRedirect && !state.compoundEnd))
) {
const rawSpan = state.input.slice(state.commandStart, state.wordEnd)
const leading = /^[ \t\n]+/.exec(rawSpan)?.[0].length ?? 0
const resource = rawSpan.slice(leading).replace(/[ \t\n]+$/g, "")
if (resource) {
const prefixEnd =
state.redirectPrefixEnd !== undefined
? Math.max(1, Math.min(resource.length, state.redirectPrefixEnd - state.commandStart - leading))
: resource.length
const prefixToken = resource.slice(0, prefixEnd)
const command: Command = {
resource,
words: [prefixToken],
rawWords: [prefixToken],
redirectPrefixEnd: prefixEnd,
}
state.commands.push(command)
owner = command
}
}
for (const heredoc of state.heredocs) {
if (owner && newline && !heredoc.owned) {
heredoc.command = owner
heredoc.start = state.commandStart
}
heredoc.owned = true
}
if (boundary && !state.words.length && !state.hasRedirect && !state.compoundEnd && !inHeader)
state.invalid ??= "invalid-structure"
if (state.words.length > (state.ampersandRedirectWords ?? Infinity)) state.invalid ??= "invalid-redirect"
state.commands.push(...state.nestedCommands.splice(0))
if (!inHeader && (state.words.length > 0 || state.hasRedirect)) bashStatement(state)
state.words.length = 0
state.rawWords.length = 0
state.commandWordIndex = -1
state.commandStart = undefined
state.dupRedirect = false
state.hasRedirect = false
state.hasFileRedirect = false
state.redirectWordCount = undefined
state.redirectPrefixEnd = undefined
state.ampersandRedirectWords = undefined
state.compoundEnd = false
state.dangling = false
}
function scanBash(
input: string,
start: number,
depth: number,
context: BashContext,
close?: ")" | "}" | "nofork",
// A group shares its parent's heredocs; a substitution starts its own.
heredocs?: BashHeredoc[],
outer?: BashText,
): BashResult {
if (depth > MAX_SUBSTITUTION_DEPTH || context.remaining < 0) return { kind: "opaque", reason: "invalid-structure" }
const state: BashState = {
input,
context,
commands: [],
nestedCommands: [],
words: [],
rawWords: [],
heredocs: heredocs ?? [],
structures: [],
word: "",
literal: "",
output: "",
wordStarted: false,
wordStart: start,
wordEnd: start,
commandStart: undefined,
redirectWordCount: undefined,
redirectPrefixEnd: undefined,
ampersandRedirectWords: undefined,
commandWordIndex: -1,
assignmentWord: false,
assignmentHeadUnsafe: false,
invalid: undefined,
redirectTarget: false,
dupRedirect: false,
hereString: false,
hasRedirect: false,
hasFileRedirect: false,
compoundEnd: false,
dangling: false,
outer,
}
for (let index = start; index < input.length; index++) {
if (--context.remaining < 0) return { kind: "opaque", reason: "invalid-structure" }
const char = input[index]
// Line continuations are removed before tokens are read.
if (char === "\\" && input[index + 1] === "\n") {
index++
continue
}
if (!state.wordStarted) {
state.wordStart = index
if (char === " " || char === "\t") continue
if (
char === "}" &&
state.words.length === 0 &&
!state.redirectTarget &&
(close === "}" || close === "nofork") &&
state.structures.length === 0 &&
(heredocs !== undefined || state.heredocs.length === 0) &&
(close === "nofork" || testAt(BRACE_CLOSE_AHEAD_RE, input, index + 1))
)
return closeBashList(state, index)
if (char === "}")
return { kind: "opaque", reason: state.structures.length ? "compound-command" : "invalid-structure" }
const step = scanBashCommandStart(state, index, depth, context)
if (typeof step === "object") return step
if (step !== undefined) {
index = step
continue
}
}
if (char === "\\" && index + 1 >= input.length) return { kind: "opaque", reason: "unterminated-escape" }
if (
!state.assignmentWord &&
("'\"\\".includes(char) || (char === "$" && (input[index + 1] === "'" || input[index + 1] === '"')))
)
state.assignmentHeadUnsafe = true
const inCasePattern = state.structures.at(-1)?.phase === "pattern"
// Elsewhere a parenthesized group inside a word is a Zsh glob qualifier, which can run code.
const array =
(char === "=" || char === "(") &&
state.assignmentWord &&
state.word.length > 1 &&
state.word.endsWith("=") &&
!state.word.endsWith("==") &&
(state.commandWordIndex < 0 || BASH_ASSIGNMENT_DECLARATIONS.has(state.rawWords[state.commandWordIndex]))
if (char === "=" && (!state.wordStarted || array) && input[index + 1] === "(") {
const end = scanBashNested(input, index + 2, depth, context, state.nestedCommands, ")")
if (typeof end === "object") return end
state.wordStarted = true
state.word += input.slice(index, end + 1)
index = end
state.wordEnd = index + 1
continue
}
const unit = BASH_UNIT_STARTS.includes(char)
? scanBashUnit(
input,
index,
depth,
context,
state.nestedCommands,
"word",
!state.assignmentWord && state.commandWordIndex >= 0 && !BASH_DECLARATIONS.has(state.rawWords[0]),
state,
)
: undefined
if (typeof unit === "object") return unit
if (unit !== undefined) {
state.wordStarted = true
index = unit
state.wordEnd = index + 1
continue
}
if (
char === "[" &&
!inCasePattern &&
!state.assignmentWord &&
!state.assignmentHeadUnsafe &&
state.commandWordIndex < 0 &&
/^[A-Za-z_][A-Za-z0-9_]*$/.test(state.word)
) {
const subscript: Command[] = []
const end = scanBashSubscript(input, index + 1, depth, context, subscript, BASH_SPANS.assignmentSubscript)
if (typeof end === "object") return end
const assign = bashOperator(input, end + 1, ["+=", "="])
if (typeof assign === "object") return assign
if (assign) {
// Dash has no arrays and word-splits unquoted expansions inside `name[subscript]=value`.
if (context.dialect === "posix" && /[$`]/.test(input.slice(index + 1, end)))
return { kind: "opaque", reason: "invalid-structure" }
state.nestedCommands.push(...subscript)
state.assignmentWord = true
state.word += input.slice(index, end + 1)
index = end
state.wordEnd = index + 1
continue
}
}
if (char === "(" && (array || ((inCasePattern || context.dialect === "bash") && /[?*+@!]$/.test(state.word)))) {
const mode = array ? "array" : "pattern"
const end = scanBashArrayOrPattern(input, index, depth + 1, context, state.nestedCommands, mode)
if (typeof end === "object") return end
if (bashCrossesHeredoc(state, index, end)) return { kind: "opaque", reason: "heredoc" }
// Zsh ends an array assignment at its closing parenthesis, so text right after it starts a command.
if (array && end + 1 < input.length && !" \t\n;&|<>)".includes(input[end + 1]))
return { kind: "opaque", reason: "invalid-structure" }
state.wordStarted = true
state.word += input.slice(index, end + 1)
index = end
state.wordEnd = index + 1
continue
}
if (char === "#" && !state.wordStarted) {
const newline = input.indexOf("\n", index)
if (newline === -1) break
index = newline - 1
continue
}
if ("<>&|;\n".includes(char)) {
const step = scanBashOperatorOrSeparator(state, index, depth, context)
if (typeof step === "object") return step
index = step
continue
}
if (inCasePattern && char === ")") {
finishBashWord(state)
index--
continue
}
if (char === ")") {
if (close !== ")" || state.structures.length > 0 || (heredocs === undefined && state.heredocs.length > 0))
return { kind: "opaque", reason: "compound-command" }
return closeBashList(state, index)
}
if (
char === "(" &&
context.dialect === "zsh" &&
state.wordStarted &&
!inCasePattern &&
testAt(ZSH_GLOB_QUALIFIER_RE, input, index)
) {
const end = ZSH_GLOB_QUALIFIER_RE.lastIndex - 1
bashAppend(state, input.slice(index, end + 1))
index = end
state.wordEnd = index + 1
continue
}
if (char === "(") return { kind: "opaque", reason: state.wordStarted ? "dynamic-execution" : "compound-command" }
if (/\s/.test(char) && !" \t\n".includes(char)) return { kind: "opaque", reason: "invalid-structure" }
if (char === " " || char === "\t") {
finishBashWord(state)
continue
}
state.wordStarted = true
if (
char === "=" &&
!state.assignmentWord &&
!state.assignmentHeadUnsafe &&
/^[A-Za-z_][A-Za-z0-9_]*\+?$/.test(state.word)
)
state.assignmentWord = true
bashAppend(state, char)
state.wordEnd = index + 1
}
if (close) return { kind: "opaque", reason: close === ")" ? "command-substitution" : "invalid-structure" }
if (state.heredocs.length) return { kind: "opaque", reason: "heredoc" }
return closeBashList(state, input.length)
}
// Steps return the last consumed index.
function scanBashOperatorOrSeparator(
state: BashState,
index: number,
depth: number,
context: BashContext,
): number | Opaque {
const input = state.input
const char = input[index]
const redirect = "<>&".includes(char) ? bashOperator(input, index, BASH_REDIRECTS) : undefined
if (typeof redirect === "object") return redirect
const caseHead = state.structures.at(-1)
if (redirect && caseHead?.kind === "case" && caseHead.phase !== "body")
return { kind: "opaque", reason: "invalid-redirect" }
if (redirect) {
state.hasRedirect = true
state.commandStart ??= state.wordStart
if (state.redirectTarget) state.invalid ??= "invalid-redirect"
const fdPrefix =
state.wordStarted && !state.assignmentHeadUnsafe && /^(?:\d+|\{[A-Za-z_][A-Za-z0-9_]*\})$/.test(state.word)
if (fdPrefix) {
state.word = ""
state.literal = ""
state.output = ""
state.wordStarted = false
}
if (!fdPrefix) finishBashWord(state)
if (redirect.startsWith("&") && context.dialect === "posix") state.ampersandRedirectWords ??= state.words.length
if (state.redirectWordCount === undefined && state.commandWordIndex >= 0) {
state.redirectWordCount = state.words.length
}
if (redirect === "<<" || redirect === "<<-") {
const delimiter = bashHeredocDelimiter(input, index + redirect.length, redirect === "<<-", context.dialect)
if (!delimiter) return { kind: "opaque", reason: "invalid-redirect" }
state.hasFileRedirect = true
state.redirectPrefixEnd ??=
" \t".includes(input[index + redirect.length] ?? "") ? index + redirect.length : delimiter.end + 1
state.heredocs.push(delimiter)
state.wordEnd = delimiter.end + 1
state.redirectTarget = false
state.dupRedirect = false
return delimiter.end
}
if (" \t\n".includes(input[index + redirect.length] ?? "")) state.redirectPrefixEnd ??= index + redirect.length
state.redirectTarget = true
state.dupRedirect = redirect === "<&" || redirect === ">&"
state.hereString = redirect === "<<<"
return index + redirect.length - 1
}
if (state.structures.at(-1)?.phase === "pattern" && char === "|") {
finishBashWord(state)
return index - 1
}
const structure = state.structures.at(-1)
const caseBody = structure?.kind === "case" && structure.phase === "body"
const operators =
context.dialect === "zsh"
? caseBody
? ZSH_CASE_OPERATORS
: ZSH_LIST_OPERATORS
: caseBody
? BASH_CASE_OPERATORS
: BASH_LIST_OPERATORS
const operator = bashOperator(input, index, operators)
if (typeof operator === "object") return operator
const separator = operator ?? char
if (caseBody && separator.startsWith(";") && separator.length > 1) {
if (!endBashList(state)) return { kind: "opaque", reason: "invalid-structure" }
structure.phase = "pattern"
structure.patternStarted = false
return index + separator.length - 1
}
if (structure?.kind === "case" && (structure.phase === "header" || structure.phase === "pattern")) {
if (separator !== "\n") return { kind: "opaque", reason: "compound-command" }
if (structure.phase === "pattern" && (state.wordStarted || state.words.length > 0))
return { kind: "opaque", reason: "compound-command" }
finishBashWord(state)
return readBashHeredocs(state, index, depth, context)
}
if (
(structure?.kind === "for" || structure?.kind === "repeat") &&
(structure.phase === "header" || structure.phase === "do")
) {
if (separator !== ";" && separator !== "\n") return { kind: "opaque", reason: "compound-command" }
if (structure.phase === "header" && !structure.sawIn && !state.wordStarted && state.words.length === 0)
return { kind: "opaque", reason: "compound-command" }
}
if (separator === "\n" && !pending(state)) return readBashHeredocs(state, index, depth, context)
if (separator === ";" && context.dialect === "zsh" && !pending(state) && !state.dangling) return index
finishBashCommand(state, true, separator === "\n")
if (structure?.kind === "for" && structure.phase === "header") structure.phase = "do"
state.dangling = !(separator === ";" || separator === "\n" || (separator.startsWith("&") && separator !== "&&"))
// Reprocess the newline to read pending heredoc bodies.
if (separator === "\n" && state.heredocs.length) return index - 1
return index + separator.length - 1
}
function bashCommandKey(command: Command) {
return JSON.stringify([command.resource, command.words])
}
// Reads the pending heredoc bodies after the newline at index and returns the last index they cover.
function readBashHeredocs(state: BashState, index: number, depth: number, context: BashContext) {
let end = index
for (const heredoc of state.heredocs.splice(0)) {
const body = bashHeredoc(state.input, end + 1, heredoc)
if (!body) return { kind: "opaque", reason: "heredoc" } satisfies Opaque
if (heredoc.command) heredoc.command.resource = state.input.slice(heredoc.start, body.end).trim()
const text = heredoc.quoted ? { word: body.source, literal: body.source, output: "" } : bashText()
if (!heredoc.quoted) {
const expansion = scanBashSpan(body.source, 0, depth, context, state.commands, BASH_SPANS.heredoc, true, text)
if (typeof expansion === "object") return expansion
}
if (heredoc.binding) bashEvaluatesExpansion(text, "deferred", context)
end = body.end
}
return end
}
// Whether a construct read as one unit holds a newline token that would start pending heredoc bodies.
function bashCrossesHeredoc(state: BashState, start: number, end: number) {
return state.heredocs.length > 0 && state.input.slice(start, end).includes("\n")
}
function scanBashCommandStart(
state: BashState,
index: number,
depth: number,
context: BashContext,
): number | Opaque | undefined {
const input = state.input
const char = input[index]
const structure = state.structures.at(-1)
if (structure?.phase === "pattern" && !structure.patternStarted && !state.words.length && char === "(") {
structure.patternStarted = true
return index
}
if (structure?.phase === "pattern" && char === "|") {
if (!state.words.length) return { kind: "opaque", reason: "compound-command" }
finishBashWord(state)
structure.patternStarted = true
return index
}
if (structure?.phase === "pattern" && char === ")") {
if (!state.words.length) return { kind: "opaque", reason: "compound-command" }
finishBashCommand(state)
structure.phase = "body"
structure.count = 0
return index
}
if (structure?.kind === "for" && structure.phase === "header" && char === "(" && input[index + 1] !== "(") {
const end = scanBashArrayOrPattern(input, index, depth + 1, context, state.nestedCommands, "array")
if (typeof end === "object") return end
if (bashCrossesHeredoc(state, index, end)) return { kind: "opaque", reason: "heredoc" }
finishBashCommand(state)
// Zsh permits a sublist or brace group directly after the value list, without do/done.
structure.phase = "do"
structure.parenthesized = true
if (!testAt(DO_AHEAD_RE, input, end + 1)) state.structures.pop()
return end
}
if (structure?.kind === "repeat" && structure.phase === "do" && char !== "\n" && char !== "#" && char !== ";") {
if (matchAt(TOKEN_RE, input, index)?.[0] !== "do") state.structures.pop()
}
const keywordStep = scanBashKeyword(state, index, depth, context)
if (keywordStep !== undefined) return keywordStep
if (structure?.kind === "for" && structure.phase === "do" && char !== "\n" && char !== "#" && char !== ";") {
if (char !== "{" || !testAt(SPACE_CONTINUATION_AHEAD_RE, input, index + 1)) return { kind: "opaque", reason: "compound-command" }
state.structures.pop()
}
const atStart = atCommandStart(state)
const functionHead = atStart && char === "(" ? bashFunctionHeadLength(input, index) : 0
if (functionHead) return index + functionHead - 1
if (atStart && char === "!") {
if (testAt(NEGATION_AHEAD_RE, input, index + 1)) return index
}
const forHeader = structure?.kind === "for" && structure.phase === "header"
const compoundOpen =
(atStart || forHeader) && "([".includes(char) ? bashOperator(input, index, ["((", "[["]) : undefined
if (typeof compoundOpen === "object") return compoundOpen
if (compoundOpen === "((") {
if (forHeader && state.words.length > 0) return { kind: "opaque", reason: "compound-command" }
const span = forHeader ? BASH_SPANS.forArithmetic : BASH_SPANS.arithmetic
const end = scanBashArithmetic(input, index + 2, depth, context, state.commands, span)
if (typeof end === "number") {
if (bashCrossesHeredoc(state, index, end)) return { kind: "opaque", reason: "heredoc" }
if (!forHeader && context.dialect === "posix") {
// Dash reads `((` as two nested subshells, so posix reports both readings.
const subshells = scanBash(input, index + 1, depth + 1, context, ")")
if (subshells.kind === "opaque") return subshells
if (subshells.end !== end) return { kind: "opaque", reason: "compound-command" }
const seen = new Set(state.commands.map(bashCommandKey))
state.commands.push(...subshells.commands.filter((command) => !seen.has(bashCommandKey(command))))
}
if (forHeader) {
structure.phase = "do"
structure.sawIn = true
}
if (!forHeader) {
bashStatement(state)
state.compoundEnd = true
}
return end
}
if (end) return end
if (forHeader) return { kind: "opaque", reason: "invalid-structure" }
}
if (
atStart &&
(char === "(" ||
(char === "{" && testAt(SPACE_CONTINUATION_AHEAD_RE, input, index + 1)))
) {
const group = scanBash(input, index + 1, depth + 1, context, char === "{" ? "}" : ")", state.heredocs)
if (group.kind === "opaque") return group
if (!input.slice(index + 1, group.end).trim()) return { kind: "opaque", reason: "invalid-structure" }
state.commands.push(...group.commands)
bashStatement(state)
state.compoundEnd = true
return group.end
}
if (
atStart &&
compoundOpen === "[[" &&
testAt(SPACE_CONTINUATION_AHEAD_RE, input, index + 2)
) {
const end = scanBashConditional(input, index + 2, depth, context, state.commands)
if (typeof end === "object") return end
if (bashCrossesHeredoc(state, index, end)) return { kind: "opaque", reason: "heredoc" }
bashStatement(state)
state.compoundEnd = true
return end
}
return undefined
}
function scanBashKeyword(
state: BashState,
index: number,
depth: number,
context: BashContext,
): number | Opaque | undefined {
const input = state.input
const char = input[index]
if (!((char >= "A" && char <= "Z") || (char >= "a" && char <= "z") || char === "_")) return undefined
const structure = state.structures.at(-1)
const token = matchAt(TOKEN_RE, input, index)?.[0]
const end = index + (token?.length ?? 0) - 1
if (structure?.kind === "case" && structure.phase === "header" && token === "in") {
if (state.words.length !== 1 || state.hasRedirect) return { kind: "opaque", reason: "compound-command" }
finishBashCommand(state)
structure.phase = "pattern"
structure.patternStarted = false
return end
}
if (
structure?.kind === "for" &&
(structure.phase === "header" || structure.phase === "do") &&
!structure.sawIn &&
!structure.parenthesized &&
token === "in" &&
(structure.phase === "do" || state.words.length >= 1)
) {
structure.sawIn = true
structure.phase = "header"
return end
}
if (structure?.phase === "pattern" && !structure.patternStarted && !state.words.length && token === "esac") {
state.structures.pop()
bashStatement(state)
state.compoundEnd = true
return end
}
// POSIX `for name do` omits the in list.
if (
structure?.kind === "for" &&
structure.phase === "header" &&
!structure.sawIn &&
state.words.length === 1 &&
!state.hasRedirect &&
token === "do"
) {
finishBashCommand(state)
structure.phase = "do"
}
const inHeader = bashInHeader(state)
if (
token &&
["then", "elif", "else", "fi", "do", "done", "esac"].includes(token) &&
!state.words.length &&
!state.redirectTarget &&
(!inHeader || (token === "do" && structure?.phase === "do"))
) {
// Bash and Dash read a reserved word after a redirect as a command word, while Zsh reads a keyword.
if ((state.hasRedirect && context.dialect !== "zsh") || !endBashList(state) || !structure)
return { kind: "opaque", reason: "compound-command" }
if (token === "then") {