Debian Codegraph @

expand/expand.go

raw
1 // Copyright (c) 2017, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 package expand
5
6 import (
7 "cmp"
8 "errors"
9 "fmt"
10 "io"
11 "io/fs"
12 "iter"
13 "maps"
14 "os"
15 "os/user"
16 "path/filepath"
17 "regexp"
18 "runtime"
19 "slices"
20 "strconv"
21 "strings"
22 "syscall"
23 "unicode/utf8"
24
25 "mvdan.cc/sh/v3/internal"
26 "mvdan.cc/sh/v3/pattern"
27 "mvdan.cc/sh/v3/syntax"
28 )
29
30 // A Config specifies details about how shell expansion should be performed. The
31 // zero value is a valid configuration.
32 type Config struct {
33 // Env is used to get and set environment variables when performing
34 // shell expansions. Some special parameters are also expanded via this
35 // interface, such as:
36 //
37 // * "#", "@", "*", "0"-"9" for the shell's parameters
38 // * "?", "$", "PPID" for the shell's status and process
39 // * "HOME foo" to retrieve user foo's home directory (if unset,
40 // os/user.Lookup will be used)
41 //
42 // If nil, there are no environment variables set. Use
43 // ListEnviron(os.Environ()...) to use the system's environment
44 // variables.
45 Env Environ
46
47 // CmdSubst expands a command substitution node, writing its standard
48 // output to the provided [io.Writer].
49 //
50 // If nil, encountering a command substitution will result in an
51 // UnexpectedCommandError.
52 CmdSubst func(io.Writer, *syntax.CmdSubst) error
53
54 // ProcSubst expands a process substitution node.
55 ProcSubst func(*syntax.ProcSubst) (string, error)
56
57 // TODO(v4): replace ReadDir with ReadDir2.
58
59 // ReadDir is the older form of [ReadDir2], before io/fs.
60 //
61 // Deprecated: use ReadDir2 instead.
62 ReadDir func(string) ([]fs.FileInfo, error)
63
64 // ReadDir2 is used for file path globbing.
65 // If nil, and [ReadDir] is nil as well, globbing is disabled.
66 // Use [os.ReadDir] to use the filesystem directly.
67 ReadDir2 func(string) ([]fs.DirEntry, error)
68
69 // GlobStar corresponds to the shell option which allows globbing with "**".
70 GlobStar bool
71
72 // DotGlob corresponds to the shell option which allows filenames beginning
73 // with a dot to be matched by a pattern which does not begin with a dot.
74 DotGlob bool
75
76 // NoCaseGlob corresponds to the shell option which causes case-insensitive
77 // pattern matching in pathname expansion.
78 NoCaseGlob bool
79
80 // NullGlob corresponds to the shell option which allows globbing
81 // patterns which match nothing to result in zero fields.
82 NullGlob bool
83
84 // NoUnset corresponds to the shell option which treats unset variables
85 // as errors.
86 NoUnset bool
87
88 // ExtGlob corresponds to the shell option which allows using extended
89 // pattern matching features when performing pathname expansion (globbing).
90 ExtGlob bool
91
92 bufferAlloc strings.Builder
93 fieldAlloc [4]fieldPart
94 fieldsAlloc [4][]fieldPart
95
96 ifs string
97 // A pointer to a parameter expansion node, if we're inside one.
98 // Necessary for ${LINENO}.
99 curParam *syntax.ParamExp
100 }
101
102 // UnexpectedCommandError is returned if a command substitution is encountered
103 // when [Config.CmdSubst] is nil.
104 type UnexpectedCommandError struct {
105 Node *syntax.CmdSubst
106 }
107
108 func (u UnexpectedCommandError) Error() string {
109 return fmt.Sprintf("unexpected command substitution at %s", u.Node.Pos())
110 }
111
112 var zeroConfig = &Config{}
113
114 // TODO: note that prepareConfig is modifying the user's config in place,
115 // which doesn't feel right - we should make a copy.
116
117 func prepareConfig(cfg *Config) *Config {
118 cfg = cmp.Or(cfg, zeroConfig)
119 cfg.Env = cmp.Or(cfg.Env, FuncEnviron(func(string) string { return "" }))
120
121 cfg.ifs = " \t\n"
122 if vr := cfg.Env.Get("IFS"); vr.IsSet() {
123 cfg.ifs = vr.String()
124 }
125
126 if cfg.ReadDir != nil && cfg.ReadDir2 == nil {
127 cfg.ReadDir2 = func(path string) ([]fs.DirEntry, error) {
128 infos, err := cfg.ReadDir(path)
129 if err != nil {
130 return nil, err
131 }
132 entries := make([]fs.DirEntry, len(infos))
133 for i, info := range infos {
134 entries[i] = fs.FileInfoToDirEntry(info)
135 }
136 return entries, nil
137 }
138 }
139 return cfg
140 }
141
142 func (cfg *Config) ifsRune(r rune) bool {
143 return strings.ContainsRune(cfg.ifs, r)
144 }
145
146 // ifsWhitespace reports whether r is a space, tab, or newline present in IFS.
147 func (cfg *Config) ifsWhitespace(r rune) bool {
148 return (r == ' ' || r == '\t' || r == '\n') && cfg.ifsRune(r)
149 }
150
151 func (cfg *Config) ifsJoin(strs []string) string {
152 sep := ""
153 if cfg.ifs != "" {
154 // The separator is the first character of IFS, not the first byte.
155 _, size := utf8.DecodeRuneInString(cfg.ifs)
156 sep = cfg.ifs[:size]
157 }
158 return strings.Join(strs, sep)
159 }
160
161 func (cfg *Config) strBuilder() *strings.Builder {
162 b := &cfg.bufferAlloc
163 b.Reset()
164 return b
165 }
166
167 func (cfg *Config) envGet(name string) string {
168 return cfg.Env.Get(name).String()
169 }
170
171 func (cfg *Config) envSet(name, value string) error {
172 wenv, ok := cfg.Env.(WriteEnviron)
173 if !ok {
174 return fmt.Errorf("environment is read-only")
175 }
176 return wenv.Set(name, Variable{Set: true, Kind: String, Str: value})
177 }
178
179 // Literal expands a single shell word. It is similar to [Fields], but the result
180 // is a single string. This is the behavior when a word is used as the value in
181 // a shell variable assignment, for example.
182 //
183 // The config specifies shell expansion options; nil behaves the same as an
184 // empty config.
185 func Literal(cfg *Config, word *syntax.Word) (string, error) {
186 if word == nil {
187 return "", nil
188 }
189 cfg = prepareConfig(cfg)
190 field, err := cfg.wordField(word.Parts, quoteNone)
191 if err != nil {
192 return "", err
193 }
194 return cfg.fieldJoin(field), nil
195 }
196
197 // Document expands a single shell word as if it were a here-document body.
198 // It is similar to [Literal], but without brace expansion, tilde expansion, and
199 // globbing.
200 //
201 // The config specifies shell expansion options; nil behaves the same as an
202 // empty config.
203 func Document(cfg *Config, word *syntax.Word) (string, error) {
204 if word == nil {
205 return "", nil
206 }
207 cfg = prepareConfig(cfg)
208 field, err := cfg.wordField(word.Parts, quoteHeredoc)
209 if err != nil {
210 return "", err
211 }
212 return cfg.fieldJoin(field), nil
213 }
214
215 // Pattern expands a single shell word as a pattern, using [pattern.QuoteMeta]
216 // on any non-quoted parts of the input word. The result can be used on
217 // [pattern.Regexp] directly.
218 //
219 // The config specifies shell expansion options; nil behaves the same as an
220 // empty config.
221 func Pattern(cfg *Config, word *syntax.Word) (string, error) {
222 if word == nil {
223 return "", nil
224 }
225 cfg = prepareConfig(cfg)
226 field, err := cfg.wordField(word.Parts, quoteNone)
227 if err != nil {
228 return "", err
229 }
230 sb := cfg.strBuilder()
231 for _, part := range field {
232 if part.quote > quoteNone {
233 sb.WriteString(pattern.QuoteMeta(part.val, 0))
234 } else {
235 sb.WriteString(part.val)
236 }
237 }
238 return sb.String(), nil
239 }
240
241 // Format expands a format string with a number of arguments, following the
242 // shell's format specifications. These include printf(1), among others.
243 //
244 // The resulting string is returned, along with the number of arguments used.
245 // Note that the resulting string may contain null bytes, for example
246 // if the format string used `\x00`. The caller should terminate the string
247 // at the first null byte if needed, such as when expanding for `$'foo\x00bar'`.
248 //
249 // The config specifies shell expansion options; nil behaves the same as an
250 // empty config.
251 func Format(cfg *Config, format string, args []string) (string, int, error) {
252 cfg = prepareConfig(cfg)
253 sb := cfg.strBuilder()
254
255 consumed, err := formatInto(sb, format, args)
256 if err != nil {
257 return "", 0, err
258 }
259
260 return sb.String(), consumed, err
261 }
262
263 func formatInto(sb *strings.Builder, format string, args []string) (int, error) {
264 var fmts []byte
265 initialArgs := len(args)
266
267 for i := 0; i < len(format); i++ {
268 // readDigits reads from 0 to max digits, either octal or
269 // hexadecimal.
270 readDigits := func(max int, hex bool) string {
271 j := 0
272 for ; j < max && i+j < len(format); j++ {
273 c := format[i+j]
274 if (c >= '0' && c <= '9') ||
275 (hex && c >= 'a' && c <= 'f') ||
276 (hex && c >= 'A' && c <= 'F') {
277 // valid octal or hex char
278 } else {
279 break
280 }
281 }
282 digits := format[i : i+j]
283 i += j - 1 // -1 since the outer loop does i++
284 return digits
285 }
286 c := format[i]
287 switch {
288 case c == '\\': // escaped
289 i++
290 if i >= len(format) {
291 sb.WriteByte('\\')
292 break
293 }
294 switch c = format[i]; c {
295 case 'a': // bell
296 sb.WriteByte('\a')
297 case 'b': // backspace
298 sb.WriteByte('\b')
299 case 'e', 'E': // escape
300 sb.WriteByte('\x1b')
301 case 'f': // form feed
302 sb.WriteByte('\f')
303 case 'n': // new line
304 sb.WriteByte('\n')
305 case 'r': // carriage return
306 sb.WriteByte('\r')
307 case 't': // horizontal tab
308 sb.WriteByte('\t')
309 case 'v': // vertical tab
310 sb.WriteByte('\v')
311 case '\\', '\'', '"', '?': // just the character
312 sb.WriteByte(c)
313 case '0', '1', '2', '3', '4', '5', '6', '7':
314 digits := readDigits(3, false)
315 // if digits don't fit in 8 bits, 0xff via strconv
316 n, _ := strconv.ParseUint(digits, 8, 8)
317 sb.WriteByte(byte(n))
318 case 'x', 'u', 'U':
319 i++
320 max := 2
321 switch c {
322 case 'u':
323 max = 4
324 case 'U':
325 max = 8
326 }
327 digits := readDigits(max, true)
328 if len(digits) > 0 {
329 // can't error
330 n, _ := strconv.ParseUint(digits, 16, 32)
331 if c == 'x' {
332 // always as a single byte
333 sb.WriteByte(byte(n))
334 } else {
335 sb.WriteRune(rune(n))
336 }
337 break
338 }
339 fallthrough
340 default: // no escape sequence
341 sb.WriteByte('\\')
342 sb.WriteByte(c)
343 }
344 case len(fmts) > 0:
345 switch c {
346 case '%':
347 sb.WriteByte('%')
348 fmts = nil
349 case 'c':
350 var b byte
351 if len(args) > 0 {
352 arg := ""
353 arg, args = args[0], args[1:]
354 if len(arg) > 0 {
355 b = arg[0]
356 }
357 }
358 sb.WriteByte(b)
359 fmts = nil
360 case '+', '-', ' ':
361 if len(fmts) > 1 {
362 return 0, fmt.Errorf("invalid format char: %c", c)
363 }
364 fmts = append(fmts, c)
365 case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
366 fmts = append(fmts, c)
367 case 's', 'b', 'd', 'i', 'u', 'o', 'x':
368 arg := ""
369 if len(args) > 0 {
370 arg, args = args[0], args[1:]
371 }
372 var farg any
373 if c == 'b' {
374 // Passing in nil for args ensures that % format
375 // strings aren't processed; only escape sequences
376 // will be handled.
377 _, err := formatInto(sb, arg, nil)
378 if err != nil {
379 return 0, err
380 }
381 } else if c != 's' {
382 n, _ := strconv.ParseInt(arg, 0, 0)
383 if c == 'i' || c == 'd' {
384 farg = int(n)
385 } else {
386 farg = uint(n)
387 }
388 if c == 'i' || c == 'u' {
389 c = 'd'
390 }
391 } else {
392 farg = arg
393 }
394 if farg != nil {
395 fmts = append(fmts, c)
396 fmt.Fprintf(sb, string(fmts), farg)
397 }
398 fmts = nil
399 default:
400 return 0, fmt.Errorf("invalid format char: %c", c)
401 }
402 case args != nil && c == '%':
403 // if args == nil, we are not doing format
404 // arguments
405 fmts = []byte{c}
406 default:
407 sb.WriteByte(c)
408 }
409 }
410 if len(fmts) > 0 {
411 return 0, fmt.Errorf("missing format char")
412 }
413 return initialArgs - len(args), nil
414 }
415
416 func (cfg *Config) fieldJoin(parts []fieldPart) string {
417 switch len(parts) {
418 case 0:
419 return ""
420 case 1: // short-cut without a string copy
421 return parts[0].val
422 }
423 sb := cfg.strBuilder()
424 for _, part := range parts {
425 sb.WriteString(part.val)
426 }
427 return sb.String()
428 }
429
430 func (cfg *Config) escapedGlobField(parts []fieldPart) (escaped string, glob bool) {
431 candidate := false
432 for _, part := range parts {
433 if part.quote == quoteNone && strings.ContainsAny(part.val, "*?[") {
434 candidate = true
435 break
436 }
437 }
438 if !candidate {
439 return "", false
440 }
441 sb := cfg.strBuilder()
442 for _, part := range parts {
443 if part.quote > quoteNone {
444 sb.WriteString(pattern.QuoteMeta(part.val, 0))
445 } else {
446 sb.WriteString(part.val)
447 }
448 }
449 // Check the entire escaped word, as a bracket expression could span
450 // multiple unquoted parts, such as `[a$x` where x holds "]".
451 escaped = sb.String()
452 if pattern.HasMeta(escaped, 0) {
453 return escaped, true
454 }
455 return "", false
456 }
457
458 // Fields is a pre-iterators API which now wraps [FieldsSeq].
459 func Fields(cfg *Config, words ...*syntax.Word) ([]string, error) {
460 var fields []string
461 for s, err := range FieldsSeq(cfg, words...) {
462 if err != nil {
463 return nil, err
464 }
465 fields = append(fields, s)
466 }
467 return fields, nil
468 }
469
470 // FieldsSeq expands a number of words as if they were arguments in a shell
471 // command. This includes brace expansion, tilde expansion, parameter expansion,
472 // command substitution, arithmetic expansion, quote removal, and globbing.
473 func FieldsSeq(cfg *Config, words ...*syntax.Word) iter.Seq2[string, error] {
474 cfg = prepareConfig(cfg)
475 dir := cfg.envGet("PWD")
476 return func(yield func(string, error) bool) {
477 expandWord := func(w *syntax.Word) (stop bool) {
478 wfields, err := cfg.wordFields(w.Parts)
479 if err != nil {
480 yield("", err)
481 return true
482 }
483 for _, field := range wfields {
484 path, doGlob := cfg.escapedGlobField(field)
485 if doGlob && cfg.ReadDir2 != nil {
486 // Note that globbing requires keeping a slice state, so it doesn't
487 // really benefit from using an iterator.
488 matches, err := cfg.glob(dir, path)
489 if err != nil {
490 // We avoid [errors.As] as it allocates,
491 // and we know that [Config.glob] returns [pattern.Regexp] errors without wrapping.
492 if _, ok := err.(*pattern.SyntaxError); !ok {
493 yield("", err)
494 return true
495 }
496 } else if len(matches) > 0 || cfg.NullGlob {
497 for _, m := range matches {
498 if !yield(m, nil) {
499 return true
500 }
501 }
502 continue
503 }
504 }
505 if !yield(cfg.fieldJoin(field), nil) {
506 return true
507 }
508 }
509 return false
510 }
511 for _, word := range words {
512 word := *word // make a copy, since SplitBraces replaces the Parts slice
513 if !syntax.SplitBraces(&word) {
514 if expandWord(&word) {
515 return
516 }
517 continue
518 }
519 for w, err := range BracesSeq(cfg, &word) {
520 if err != nil {
521 yield("", err)
522 return
523 }
524 if expandWord(w) {
525 return
526 }
527 }
528 }
529 }
530 }
531
532 type fieldPart struct {
533 val string
534 quote quoteLevel
535 }
536
537 type quoteLevel uint
538
539 const (
540 quoteNone quoteLevel = iota
541 quoteDouble
542 quoteHeredoc
543 quoteSingle
544 )
545
546 func (cfg *Config) wordField(wps []syntax.WordPart, ql quoteLevel) ([]fieldPart, error) {
547 var field []fieldPart
548 for i, wp := range wps {
549 switch wp := wp.(type) {
550 case *syntax.Lit:
551 s := wp.Value
552 if i == 0 && ql == quoteNone {
553 if prefix, rest := cfg.expandUser(s, len(wps) > 1); prefix != "" {
554 // TODO: return two separate fieldParts,
555 // like in wordFields?
556 s = prefix + rest
557 }
558 }
559 if (ql == quoteDouble || ql == quoteHeredoc) && strings.Contains(s, "\\") {
560 sb := cfg.strBuilder()
561 for i := 0; i < len(s); i++ {
562 b := s[i]
563 if b == '\\' && i+1 < len(s) {
564 switch s[i+1] {
565 case '"':
566 if ql != quoteDouble {
567 break
568 }
569 fallthrough
570 case '\\', '$', '`': // special chars
571 i++
572 b = s[i] // write the special char, skipping the backslash
573 }
574 }
575 sb.WriteByte(b)
576 }
577 s = sb.String()
578 }
579 s, _, _ = strings.Cut(s, "\x00") // TODO: why is this needed?
580 field = append(field, fieldPart{val: s})
581 case *syntax.SglQuoted:
582 fp := fieldPart{quote: quoteSingle, val: wp.Value}
583 if wp.Dollar {
584 fp.val, _, _ = Format(cfg, fp.val, nil)
585 fp.val, _, _ = strings.Cut(fp.val, "\x00") // cut the string if format included \x00
586 }
587 field = append(field, fp)
588 case *syntax.DblQuoted:
589 wfield, err := cfg.wordField(wp.Parts, quoteDouble)
590 if err != nil {
591 return nil, err
592 }
593 for _, part := range wfield {
594 part.quote = quoteDouble
595 field = append(field, part)
596 }
597 case *syntax.ParamExp:
598 val, err := cfg.paramExp(wp)
599 if err != nil {
600 return nil, err
601 }
602 field = append(field, fieldPart{val: val})
603 case *syntax.CmdSubst:
604 val, err := cfg.cmdSubst(wp)
605 if err != nil {
606 return nil, err
607 }
608 field = append(field, fieldPart{val: val})
609 case *syntax.ArithmExp:
610 n, err := Arithm(cfg, wp.X)
611 if err != nil {
612 return nil, err
613 }
614 field = append(field, fieldPart{val: strconv.Itoa(n)})
615 case *syntax.ProcSubst:
616 path, err := cfg.ProcSubst(wp)
617 if err != nil {
618 return nil, err
619 }
620 field = append(field, fieldPart{val: path})
621 case *syntax.ExtGlob:
622 // Like how [Config.wordFields] deals with [syntax.ExtGlob],
623 // except that we allow these through even when [Config.ExtGlob]
624 // is false, as it only applies to pathname expansion.
625 field = append(field, fieldPart{val: wp.Op.String() + wp.Pattern.Value + ")"})
626 default:
627 panic(fmt.Sprintf("unhandled word part: %T", wp))
628 }
629 }
630 return field, nil
631 }
632
633 func (cfg *Config) cmdSubst(cs *syntax.CmdSubst) (string, error) {
634 if cfg.CmdSubst == nil {
635 return "", UnexpectedCommandError{Node: cs}
636 }
637 sb := cfg.strBuilder()
638 if err := cfg.CmdSubst(sb, cs); err != nil {
639 return "", err
640 }
641 out := sb.String()
642 out = strings.ReplaceAll(out, "\x00", "")
643 return strings.TrimRight(out, "\n"), nil
644 }
645
646 func (cfg *Config) wordFields(wps []syntax.WordPart) ([][]fieldPart, error) {
647 fields := cfg.fieldsAlloc[:0]
648 curField := cfg.fieldAlloc[:0]
649 allowEmpty := false
650 flush := func() {
651 if len(curField) == 0 {
652 return
653 }
654 fields = append(fields, curField)
655 curField = nil
656 }
657 splitAdd := func(val string) {
658 fieldStart := -1
659 for i, r := range val {
660 if cfg.ifsRune(r) {
661 if fieldStart >= 0 { // ending a field
662 curField = append(curField, fieldPart{val: val[fieldStart:i]})
663 fieldStart = -1
664 }
665 flush()
666 } else {
667 if fieldStart < 0 { // starting a new field
668 fieldStart = i
669 }
670 }
671 }
672 if fieldStart >= 0 { // ending a field without IFS
673 curField = append(curField, fieldPart{val: val[fieldStart:]})
674 }
675 }
676 for i, wp := range wps {
677 switch wp := wp.(type) {
678 case *syntax.Lit:
679 s := wp.Value
680 if i == 0 {
681 prefix, rest := cfg.expandUser(s, len(wps) > 1)
682 curField = append(curField, fieldPart{
683 quote: quoteSingle,
684 val: prefix,
685 })
686 s = rest
687 }
688 if strings.Contains(s, "\\") {
689 sb := cfg.strBuilder()
690 for i := 0; i < len(s); i++ {
691 b := s[i]
692 if b == '\\' {
693 if i++; i >= len(s) {
694 sb.WriteByte(b)
695 break
696 }
697 b = s[i]
698 }
699 sb.WriteByte(b)
700 }
701 s = sb.String()
702 }
703 curField = append(curField, fieldPart{val: s})
704 case *syntax.SglQuoted:
705 allowEmpty = true
706 fp := fieldPart{quote: quoteSingle, val: wp.Value}
707 if wp.Dollar {
708 fp.val, _, _ = Format(cfg, fp.val, nil)
709 fp.val, _, _ = strings.Cut(fp.val, "\x00") // cut the string if format included \x00
710 }
711 curField = append(curField, fp)
712 case *syntax.DblQuoted:
713 if len(wp.Parts) == 1 {
714 pe, _ := wp.Parts[0].(*syntax.ParamExp)
715 elems, err := cfg.quotedElemFields(pe)
716 if err != nil {
717 return nil, err
718 }
719 if elems != nil {
720 for i, elem := range elems {
721 if i > 0 {
722 flush()
723 }
724 curField = append(curField, fieldPart{
725 quote: quoteDouble,
726 val: elem,
727 })
728 }
729 continue
730 }
731 }
732 allowEmpty = true
733 wfield, err := cfg.wordField(wp.Parts, quoteDouble)
734 if err != nil {
735 return nil, err
736 }
737 for _, part := range wfield {
738 part.quote = quoteDouble
739 curField = append(curField, part)
740 }
741 case *syntax.ParamExp:
742 if elems, ok := cfg.unquotedElemFields(wp); ok {
743 // Unquoted "*" or "@" expansions produce one field per
744 // element; joining and re-splitting them would lose
745 // fields when IFS is empty.
746 for j, elem := range elems {
747 if j > 0 {
748 flush()
749 }
750 splitAdd(elem)
751 }
752 continue
753 }
754 val, err := cfg.paramExp(wp)
755 if err != nil {
756 return nil, err
757 }
758 splitAdd(val)
759 case *syntax.CmdSubst:
760 val, err := cfg.cmdSubst(wp)
761 if err != nil {
762 return nil, err
763 }
764 splitAdd(val)
765 case *syntax.ArithmExp:
766 n, err := Arithm(cfg, wp.X)
767 if err != nil {
768 return nil, err
769 }
770 curField = append(curField, fieldPart{val: strconv.Itoa(n)})
771 case *syntax.ProcSubst:
772 path, err := cfg.ProcSubst(wp)
773 if err != nil {
774 return nil, err
775 }
776 splitAdd(path)
777 case *syntax.ExtGlob:
778 if !cfg.ExtGlob {
779 return nil, fmt.Errorf("extended globbing operator used without the \"extglob\" option set")
780 }
781 // We don't translate or interpret the pattern here in any way;
782 // that's done later when globbing takes place via [pattern.Regexp].
783 // Here, all we do is keep the extended globbing expression in string form.
784 //
785 // TODO(v4): perhaps the syntax parser should keep extended globbing expressions
786 // as plain literal strings, because a custom node is not particularly helpful.
787 // It's not like other globbing operators like `*` or `**` get their own nodes.
788 curField = append(curField, fieldPart{val: wp.Op.String() + wp.Pattern.Value + ")"})
789 default:
790 panic(fmt.Sprintf("unhandled word part: %T", wp))
791 }
792 }
793 flush()
794 if allowEmpty && len(fields) == 0 {
795 fields = append(fields, curField)
796 }
797 return fields, nil
798 }
799
800 // listElems returns the elements of a "*" or "@" expansion of a list, like
801 // $@ or ${arr[*]}, with star set for the "*" forms which join into a single
802 // field when quoted. ok is false for any other parameter expansion.
803 func (cfg *Config) listElems(pe *syntax.ParamExp) (elems []string, star, ok bool) {
804 if pe.Param == nil { // e.g. zsh's ${}; paramExp rejects it
805 return nil, false, false
806 }
807 switch name := pe.Param.Value; name {
808 case "*", "@":
809 return cfg.sliceElems(pe, cfg.Env.Get(name).List, nil, true), name == "*", true
810 }
811 switch lit := nodeLit(pe.Index); lit {
812 case "@", "*":
813 switch vr := cfg.Env.Get(pe.Param.Value); vr.Kind {
814 case Indexed:
815 return cfg.sliceElems(pe, vr.List, vr.Indexes, false), lit == "*", true
816 case Associative:
817 return slices.Sorted(maps.Values(vr.Map)), lit == "*", true
818 }
819 }
820 return nil, false, false
821 }
822
823 // unquotedElemFields returns the elements of an unquoted "*" or "@" list
824 // expansion like $* or ${foo[@]}; ok is false for any other expansion.
825 func (cfg *Config) unquotedElemFields(pe *syntax.ParamExp) ([]string, bool) {
826 if pe.Excl || pe.Length || pe.Width || pe.IsSet || pe.Repl != nil || pe.Exp != nil {
827 return nil, false
828 }
829 elems, _, ok := cfg.listElems(pe)
830 return elems, ok
831 }
832
833 // quotedElemFields returns the list of elements resulting from a quoted
834 // parameter expansion that should be treated especially, like "${foo[@]}".
835 // The result is nil for any other parameter expansion.
836 func (cfg *Config) quotedElemFields(pe *syntax.ParamExp) ([]string, error) {
837 if pe == nil || pe.Param == nil || pe.Length || pe.Width || pe.IsSet {
838 return nil, nil
839 }
840 name := pe.Param.Value
841 if pe.Excl {
842 switch pe.Names {
843 case syntax.NamesPrefixWords: // "${!prefix@}"
844 return cfg.namesByPrefix(pe.Param.Value), nil
845 case syntax.NamesPrefix: // "${!prefix*}"
846 return nil, nil
847 }
848 switch nodeLit(pe.Index) {
849 case "@": // "${!name[@]}"
850 switch vr := cfg.Env.Get(name); vr.Kind {
851 case Indexed:
852 return vr.indexedKeys(), nil
853 case Associative:
854 return slices.Collect(maps.Keys(vr.Map)), nil
855 }
856 }
857 return nil, nil
858 }
859 if elems, star, ok := cfg.listElems(pe); ok {
860 // Operators like "${foo[@]#prefix}" apply to each element.
861 elems, err := cfg.perElemOps(pe, elems)
862 if err != nil {
863 return nil, err
864 }
865 if star {
866 return []string{cfg.ifsJoin(elems)}, nil
867 }
868 return elems, nil
869 }
870 if nodeLit(pe.Index) == "@" && !cfg.Env.Get(name).IsSet() {
871 // An unset "${name[@]}" produces zero fields, like an empty array.
872 return []string{}, nil
873 }
874 return nil, nil
875 }
876
877 // sliceElems applies ${var:offset:length} slicing to a list of elements.
878 // When positional is true, $0 is prepended to the list before slicing.
879 // In bash, positional parameter offsets ($@ and $*) are 1-based and
880 // offset 0 includes $0 (the shell or script name). Negative offsets
881 // count from $# + 1, so $0 is reachable via large enough negative values.
882 // A non-nil indexes records the index of each element in a sparse array;
883 // see [Variable.Indexes].
884 func (cfg *Config) sliceElems(pe *syntax.ParamExp, elems []string, indexes []int, positional bool) []string {
885 if pe.Slice == nil {
886 return elems
887 }
888 if positional {
889 elems = append([]string{cfg.Env.Get("0").Str}, elems...)
890 }
891 slicePos := func(n int) int {
892 if n < 0 {
893 n = len(elems) + n
894 if n < 0 {
895 n = len(elems)
896 }
897 } else if n > len(elems) {
898 n = len(elems)
899 }
900 return n
901 }
902 if pe.Slice.Offset != nil {
903 offset, err := Arithm(cfg, pe.Slice.Offset)
904 if err != nil {
905 return elems
906 }
907 if len(indexes) > 0 {
908 // Sparse arrays slice by index: a negative offset counts
909 // from one past the maximum index, and the result begins
910 // with the first element whose index is at least the offset.
911 if offset < 0 {
912 offset += indexes[len(indexes)-1] + 1
913 if offset < 0 {
914 offset = indexes[len(indexes)-1] + 1
915 }
916 }
917 pos, _ := slices.BinarySearch(indexes, offset)
918 elems = elems[pos:]
919 } else {
920 elems = elems[slicePos(offset):]
921 }
922 }
923 if pe.Slice.Length != nil {
924 length, err := Arithm(cfg, pe.Slice.Length)
925 if err != nil {
926 return elems
927 }
928 elems = elems[:slicePos(length)]
929 }
930 return elems
931 }
932
933 func (cfg *Config) expandUser(field string, moreFields bool) (prefix, rest string) {
934 name, ok := strings.CutPrefix(field, "~")
935 if !ok {
936 // No tilde prefix to expand, e.g. "foo".
937 return "", field
938 }
939 i := strings.IndexByte(name, '/')
940 if i < 0 && moreFields {
941 // There is a tilde prefix, but followed by more fields, e.g. "~'foo'".
942 // We only proceed if an unquoted slash was found in this field, e.g. "~/'foo'".
943 return "", field
944 }
945 if i >= 0 {
946 rest = name[i:]
947 name = name[:i]
948 }
949 if name == "" {
950 // Current user; try via "HOME", otherwise fall back to the
951 // system's appropriate home dir env var. Don't use os/user, as
952 // that's overkill. We can't use [os.UserHomeDir], because we want
953 // to use cfg.Env, and we always want to check "HOME" first.
954
955 if vr := cfg.Env.Get("HOME"); vr.IsSet() {
956 return vr.String(), rest
957 }
958
959 if runtime.GOOS == "windows" {
960 if vr := cfg.Env.Get("USERPROFILE"); vr.IsSet() {
961 return vr.String(), rest
962 }
963 }
964 return "", field
965 }
966
967 // Not the current user; try via "HOME <name>", otherwise fall back to
968 // os/user. There isn't a way to lookup user home dirs without cgo.
969
970 if vr := cfg.Env.Get("HOME " + name); vr.IsSet() {
971 return vr.String(), rest
972 }
973
974 u, err := user.Lookup(name)
975 if err != nil {
976 return "", field
977 }
978 return u.HomeDir, rest
979 }
980
981 func findAllIndex(pat, name string, n int) [][]int {
982 expr, err := pattern.Regexp(pat, 0)
983 if err != nil {
984 return nil
985 }
986 rx := regexp.MustCompile(expr)
987 return rx.FindAllStringIndex(name, n)
988 }
989
990 var (
991 rxGlobStar = regexp.MustCompile(`^[^/.][^/]*$`)
992 rxGlobStarDotGlob = regexp.MustCompile(`^[^/]*$`)
993 )
994
995 // pathJoin2 is a simpler version of [filepath.Join] without cleaning the result,
996 // since that's needed for globbing.
997 func pathJoin2(elem1, elem2 string) string {
998 if elem1 == "" {
999 return elem2
1000 }
1001 if strings.HasSuffix(elem1, string(filepath.Separator)) {
1002 return elem1 + elem2
1003 }
1004 return elem1 + string(filepath.Separator) + elem2
1005 }
1006
1007 // pathSplit splits a file path into its elements, retaining empty ones. Before
1008 // splitting, slashes are replaced with [filepath.Separator], so that splitting
1009 // Unix paths on Windows works as well.
1010 func pathSplit(path string) []string {
1011 path = filepath.FromSlash(path)
1012 return strings.Split(path, string(filepath.Separator))
1013 }
1014
1015 func (cfg *Config) glob(base, pat string) ([]string, error) {
1016 parts := pathSplit(pat)
1017 matches := []string{""}
1018 if filepath.IsAbs(pat) {
1019 if parts[0] == "" {
1020 // unix-like
1021 matches[0] = string(filepath.Separator)
1022 } else {
1023 // windows (for some reason it won't work without the
1024 // trailing separator)
1025 matches[0] = parts[0] + string(filepath.Separator)
1026 }
1027 parts = parts[1:]
1028 }
1029 // TODO: as an optimization, we could do chunks of the path all at once,
1030 // like doing a single stat for "/foo/bar" in "/foo/bar/*".
1031
1032 // TODO: Another optimization would be to reduce the number of ReadDir2 calls.
1033 // For example, /foo/* can end up doing one duplicate call:
1034 //
1035 // ReadDir2("/foo") to ensure that "/foo/" exists and only matches a directory
1036 // ReadDir2("/foo") glob "*"
1037
1038 for i, part := range parts {
1039 // Keep around for debugging.
1040 // log.Printf("matches %q part %d %q", matches, i, part)
1041
1042 wantDir := i < len(parts)-1
1043 switch {
1044 case part == "", part == ".", part == "..":
1045 for i, dir := range matches {
1046 matches[i] = pathJoin2(dir, part)
1047 }
1048 continue
1049 case !pattern.HasMeta(part, 0):
1050 var newMatches []string
1051 for _, dir := range matches {
1052 match := dir
1053 if !filepath.IsAbs(match) {
1054 match = filepath.Join(base, match)
1055 }
1056 match = pathJoin2(match, part)
1057 // We can't use [Config.ReadDir2] on the parent and match the directory
1058 // entry by name, because short paths on Windows break that.
1059 // Our only option is to [Config.ReadDir2] on the directory entry itself,
1060 // which can be wasteful if we only want to see if it exists,
1061 // but at least it's correct in all scenarios.
1062 if _, err := cfg.ReadDir2(match); err != nil {
1063 if errors.Is(err, syscall.ENOTDIR) {
1064 // Reading a regular file as a directory.
1065 // Note that on Windows this error also satisfies
1066 // [fs.ErrNotExist], so it must be checked first;
1067 // see https://github.com/golang/go/issues/46734.
1068 } else if errors.Is(err, fs.ErrNotExist) {
1069 continue // simply doesn't exist
1070 }
1071 if wantDir {
1072 continue // exists but not a directory
1073 }
1074 }
1075 newMatches = append(newMatches, pathJoin2(dir, part))
1076 }
1077 matches = newMatches
1078 continue
1079 case part == "**" && cfg.GlobStar:
1080 // Find all recursive matches for "**".
1081 // Note that we need the results to be in depth-first order,
1082 // and to avoid recursion, we use a slice as a stack.
1083 // Since we pop from the back, we populate the stack backwards.
1084 stack := make([]string, 0, len(matches))
1085 for _, match := range slices.Backward(matches) {
1086 // "a/**" should match "a/ a/b a/b/cfg ...";
1087 // note how the zero-match case there has a trailing separator.
1088 stack = append(stack, pathJoin2(match, ""))
1089 }
1090 matches = matches[:0]
1091 var newMatches []string // to reuse its capacity
1092 for len(stack) > 0 {
1093 dir := stack[len(stack)-1]
1094 stack = stack[:len(stack)-1]
1095 matches = append(matches, dir)
1096
1097 // If dir is not a directory, we keep the stack as-is and continue.
1098 newMatches = newMatches[:0]
1099 rx := rxGlobStar.MatchString
1100 if cfg.DotGlob {
1101 rx = rxGlobStarDotGlob.MatchString
1102 }
1103 newMatches, _ = cfg.globDir(base, dir, rx, wantDir, newMatches)
1104 for _, match := range slices.Backward(newMatches) {
1105 stack = append(stack, match)
1106 }
1107 }
1108 continue
1109 }
1110 mode := pattern.Filenames | pattern.EntireString | pattern.NoGlobStar
1111 if cfg.NoCaseGlob {
1112 mode |= pattern.NoGlobCase
1113 }
1114 if cfg.DotGlob {
1115 mode |= pattern.GlobLeadingDot
1116 }
1117 if cfg.ExtGlob {
1118 mode |= pattern.ExtendedOperators
1119 }
1120 matcher, err := internal.ExtendedPatternMatcher(part, mode)
1121 if err != nil {
1122 return nil, err
1123 }
1124 var newMatches []string
1125 for _, dir := range matches {
1126 newMatches, err = cfg.globDir(base, dir, matcher, wantDir, newMatches)
1127 if err != nil {
1128 return nil, err
1129 }
1130 }
1131 matches = newMatches
1132 }
1133 // Note that the results need to be sorted.
1134 // TODO: above we do a BFS; if we did a DFS, the matches would already be sorted.
1135 slices.Sort(matches)
1136 // Remove any empty matches left behind from "**".
1137 if len(matches) > 0 && matches[0] == "" {
1138 matches = matches[1:]
1139 }
1140 return matches, nil
1141 }
1142
1143 func (cfg *Config) globDir(base, dir string, matcher func(string) bool, wantDir bool, matches []string) ([]string, error) {
1144 fullDir := dir
1145 if !filepath.IsAbs(dir) {
1146 fullDir = filepath.Join(base, dir)
1147 }
1148 infos, err := cfg.ReadDir2(fullDir)
1149 if err != nil {
1150 // We still want to return matches, for the sake of reusing slices.
1151 return matches, err
1152 }
1153 for _, info := range infos {
1154 name := info.Name()
1155 if !wantDir {
1156 // No filtering.
1157 } else if mode := info.Type(); mode&os.ModeSymlink != 0 {
1158 // We need to know if the symlink points to a directory.
1159 // This requires an extra syscall, as [Config.ReadDir] on the parent directory
1160 // does not follow symlinks for each of the directory entries.
1161 // ReadDir is somewhat wasteful here, as we only want its error result,
1162 // but we could try to reuse its result as per the TODO in [Config.glob].
1163 if _, err := cfg.ReadDir2(filepath.Join(fullDir, info.Name())); err != nil {
1164 continue
1165 }
1166 } else if !mode.IsDir() {
1167 // Not a symlink nor a directory.
1168 continue
1169 }
1170 if matcher(name) {
1171 matches = append(matches, pathJoin2(dir, name))
1172 }
1173 }
1174 return matches, nil
1175 }
1176
1177 // ReadFields splits and returns n fields from s, like the "read" shell builtin.
1178 // If raw is set, backslash escape sequences are not interpreted.
1179 //
1180 // The config specifies shell expansion options; nil behaves the same as an
1181 // empty config.
1182 func ReadFields(cfg *Config, s string, n int, raw bool) []string {
1183 cfg = prepareConfig(cfg)
1184 type pos struct {
1185 start, end int
1186 }
1187 var fpos []pos
1188
1189 runes := make([]rune, 0, len(s))
1190 infield := false
1191 esc := false
1192 for _, r := range s {
1193 if infield {
1194 if cfg.ifsRune(r) && (raw || !esc) {
1195 fpos[len(fpos)-1].end = len(runes)
1196 infield = false
1197 }
1198 } else {
1199 if !cfg.ifsRune(r) && (raw || !esc) {
1200 fpos = append(fpos, pos{start: len(runes), end: -1})
1201 infield = true
1202 }
1203 }
1204 if r == '\\' {
1205 if raw || esc {
1206 runes = append(runes, r)
1207 }
1208 esc = !esc
1209 continue
1210 }
1211 runes = append(runes, r)
1212 esc = false
1213 }
1214 if len(fpos) == 0 {
1215 return nil
1216 }
1217 if infield {
1218 fpos[len(fpos)-1].end = len(runes)
1219 }
1220
1221 switch {
1222 case n == 1:
1223 // The single field spans the whole line minus leading and trailing
1224 // IFS whitespace; anything outside the fields is already IFS.
1225 lo, hi := 0, len(runes)
1226 for lo < fpos[0].start && cfg.ifsWhitespace(runes[lo]) {
1227 lo++
1228 }
1229 for hi > fpos[len(fpos)-1].end && cfg.ifsWhitespace(runes[hi-1]) {
1230 hi--
1231 }
1232 fpos[0].start, fpos[0].end = lo, hi
1233 fpos = fpos[:1]
1234 case n != -1 && n < len(fpos):
1235 // combine to max n fields
1236 fpos[n-1].end = fpos[len(fpos)-1].end
1237 fpos = fpos[:n]
1238 }
1239
1240 fields := make([]string, len(fpos))
1241 for i, p := range fpos {
1242 fields[i] = string(runes[p.start:p.end])
1243 }
1244 return fields
1245 }