Debian Codegraph @

expand/braces.go

raw
1 // Copyright (c) 2018, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 package expand
5
6 import (
7 "fmt"
8 "iter"
9 "slices"
10 "strconv"
11 "strings"
12
13 "mvdan.cc/sh/v3/syntax"
14 )
15
16 // Braces performs brace expansion on a word, given that it contains any
17 // [syntax.BraceExp] parts. For example, the word with a brace expansion
18 // "foo{bar,baz}" will return two literal words, "foobar" and "foobaz".
19 //
20 // Note that the resulting words may share word parts.
21 //
22 // Deprecated: use [BracesSeq], which yields words lazily and reports an
23 // error rather than letting a large sequence allocate huge amounts.
24 func Braces(word *syntax.Word) []*syntax.Word {
25 var all []*syntax.Word
26 bracesSeqRec(word, func(w *syntax.Word) bool {
27 all = append(all, w)
28 return true
29 })
30 return all
31 }
32
33 // BracesSeq performs brace expansion on a word, given that it contains any
34 // [syntax.BraceExp] parts. For example, the word with a brace expansion
35 // "foo{bar,baz}" will return two literal words, "foobar" and "foobaz".
36 //
37 // The iteration yields an error and stops if the total expansion is too
38 // large, including combinatorial blow-ups across multiple brace expansions
39 // like {1..100}{1..100}{1..100}. This may be configurable with cfg in the
40 // future; the parameter is entirely unused for now.
41 //
42 // Note that the resulting words may share word parts.
43 func BracesSeq(cfg *Config, word *syntax.Word) iter.Seq2[*syntax.Word, error] {
44 return func(yield func(*syntax.Word, error) bool) {
45 // 16Ki expanded elements is more than any script should need in practice,
46 // but it's small enough where we don't waste too much memory and CPU.
47 const limit = 16 << 10
48 count := 0
49 bracesSeqRec(word, func(w *syntax.Word) bool {
50 count++
51 if count > limit {
52 yield(nil, fmt.Errorf("brace expansion would exceed %d elements", limit))
53 return false
54 }
55 return yield(w, nil)
56 })
57 }
58 }
59
60 // bracesSeqRec yields each fully-expanded word descended from word.
61 // It returns false if iteration should stop.
62 func bracesSeqRec(word *syntax.Word, yield func(*syntax.Word) bool) bool {
63 var left []syntax.WordPart
64 for i, wp := range word.Parts {
65 br, ok := wp.(*syntax.BraceExp)
66 if !ok {
67 left = append(left, wp)
68 continue
69 }
70 rest := word.Parts[i+1:]
71 // Yield each word produced by recursing on `next`,
72 // after prepending `left` to its Parts.
73 expand := func(next *syntax.Word) bool {
74 return bracesSeqRec(next, func(w *syntax.Word) bool {
75 w.Parts = slices.Concat(left, w.Parts)
76 return yield(w)
77 })
78 }
79 if br.Sequence {
80 fromLit := br.Elems[0].Lit()
81 toLit := br.Elems[1].Lit()
82
83 chars := false
84 // ParseInt with bit size 64 to ensure consistent behavior on 32-bit platforms.
85 from, err1 := strconv.ParseInt(fromLit, 10, 64)
86 to, err2 := strconv.ParseInt(toLit, 10, 64)
87 if err1 != nil || err2 != nil {
88 chars = true
89 from = int64(fromLit[0])
90 to = int64(toLit[0])
91 }
92 // Endpoints with leading zeros pad all results to the
93 // widest endpoint, e.g. {01..10} gives 01 02 [...] 09 10.
94 width := 0
95 if !chars && (hasLeadingZeros(fromLit) || hasLeadingZeros(toLit)) {
96 width = max(len(fromLit), len(toLit))
97 }
98 upward := from <= to
99 incr := int64(1)
100 if len(br.Elems) > 2 {
101 // ParseInt with bit size 64 to ensure consistent behavior on 32-bit platforms.
102 n, _ := strconv.ParseInt(br.Elems[2].Lit(), 10, 64)
103 if n < 0 {
104 n = -n // only the absolute value of the step matters
105 }
106 if n != 0 {
107 incr = n
108 }
109 }
110 if !upward {
111 incr = -incr
112 }
113 for n := from; (upward && n <= to) || (!upward && n >= to); n += incr {
114 next := *word
115 lit := &syntax.Lit{}
116 switch {
117 case chars:
118 lit.Value = string(rune(n))
119 case width > 0:
120 lit.Value = fmt.Sprintf("%0*d", width, n)
121 default:
122 lit.Value = strconv.FormatInt(n, 10)
123 }
124 next.Parts = append([]syntax.WordPart{lit}, rest...)
125 if !expand(&next) {
126 return false
127 }
128 }
129 return true
130 }
131 for _, elem := range br.Elems {
132 next := *word
133 next.Parts = slices.Concat(elem.Parts, rest)
134 if !expand(&next) {
135 return false
136 }
137 }
138 return true
139 }
140 return yield(&syntax.Word{Parts: left})
141 }
142
143 func hasLeadingZeros(s string) bool {
144 s = strings.TrimPrefix(s, "-")
145 return len(s) > 1 && s[0] == '0'
146 }