Debian Codegraph @

expand/param.go

raw
1 // Copyright (c) 2017, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 package expand
5
6 import (
7 "fmt"
8 "maps"
9 "regexp"
10 "slices"
11 "strconv"
12 "strings"
13 "unicode"
14 "unicode/utf8"
15
16 "mvdan.cc/sh/v3/internal"
17 "mvdan.cc/sh/v3/pattern"
18 "mvdan.cc/sh/v3/syntax"
19 )
20
21 func nodeLit(node syntax.Node) string {
22 if word, ok := node.(*syntax.Word); ok {
23 return word.Lit()
24 }
25 return ""
26 }
27
28 // UnsetParameterError is returned when a parameter expansion encounters an
29 // unset variable and [Config.NoUnset] has been set.
30 type UnsetParameterError struct {
31 Node *syntax.ParamExp
32 Message string
33 }
34
35 func (u UnsetParameterError) Error() string {
36 return fmt.Sprintf("%s: %s", u.Node.Param.Value, u.Message)
37 }
38
39 func overridingUnset(pe *syntax.ParamExp) bool {
40 if pe.Exp == nil {
41 return false
42 }
43 switch pe.Exp.Op {
44 case syntax.AlternateUnset, syntax.AlternateUnsetOrNull,
45 syntax.DefaultUnset, syntax.DefaultUnsetOrNull,
46 syntax.ErrorUnset, syntax.ErrorUnsetOrNull,
47 syntax.AssignUnset, syntax.AssignUnsetOrNull:
48 return true
49 }
50 return false
51 }
52
53 func (cfg *Config) paramExp(pe *syntax.ParamExp) (string, error) {
54 oldParam := cfg.curParam
55 cfg.curParam = pe
56 defer func() { cfg.curParam = oldParam }()
57
58 if pe.Param == nil { // e.g. zsh's ${}
59 return "", fmt.Errorf("unsupported")
60 }
61 name := pe.Param.Value
62 index := pe.Index
63 switch name {
64 case "@", "*":
65 index = &syntax.Word{Parts: []syntax.WordPart{
66 &syntax.Lit{Value: name},
67 }}
68 }
69 // "*" expansions like ${*}, ${arr[*]}, or ${!prefix*} join their
70 // elements with the first IFS character; others use a space.
71 join := func(elems []string) string {
72 if nodeLit(index) == "*" || pe.Names == syntax.NamesPrefix {
73 return cfg.ifsJoin(elems)
74 }
75 return strings.Join(elems, " ")
76 }
77 var vr Variable
78 switch name {
79 case "LINENO":
80 // This is the only parameter expansion that the environment
81 // interface cannot satisfy.
82 line := uint64(cfg.curParam.Pos().Line())
83 vr = Variable{Set: true, Kind: String, Str: strconv.FormatUint(line, 10)}
84 default:
85 vr = cfg.Env.Get(name)
86 }
87 orig := vr
88 if n, v := vr.Resolve(cfg.Env); n != "" {
89 name, vr = n, v
90 }
91 if cfg.NoUnset && !vr.IsSet() && !overridingUnset(pe) {
92 return "", UnsetParameterError{
93 Node: pe,
94 Message: "unbound variable",
95 }
96 }
97
98 var sliceOffset, sliceLen int
99 if pe.Slice != nil {
100 var err error
101 if pe.Slice.Offset != nil {
102 sliceOffset, err = Arithm(cfg, pe.Slice.Offset)
103 if err != nil {
104 return "", err
105 }
106 }
107 if pe.Slice.Length != nil {
108 sliceLen, err = Arithm(cfg, pe.Slice.Length)
109 if err != nil {
110 return "", err
111 }
112 }
113 }
114
115 var (
116 str string
117 elems []string
118
119 indexAllElements bool // true if var has been accessed with * or @ index
120 callVarInd = true
121 set = vr.IsSet()
122 )
123
124 switch nodeLit(index) {
125 case "@", "*":
126 switch vr.Kind {
127 case Unknown:
128 elems = nil
129 indexAllElements = true
130 case Indexed:
131 indexAllElements = true
132 callVarInd = false
133 elems = cfg.sliceElems(pe, vr.List, vr.Indexes, name == "@" || name == "*")
134 str = join(elems)
135 }
136 }
137 if callVarInd {
138 var err error
139 str, set, err = cfg.varInd(vr, index)
140 if err != nil {
141 return "", err
142 }
143 }
144 if !indexAllElements {
145 elems = []string{str}
146 }
147
148 switch {
149 case pe.Length:
150 n := len(elems)
151 switch nodeLit(index) {
152 case "@", "*":
153 default:
154 n = utf8.RuneCountInString(str)
155 }
156 str = strconv.Itoa(n)
157 case pe.Excl:
158 var strs []string
159 switch {
160 case pe.Names != 0:
161 strs = cfg.namesByPrefix(pe.Param.Value)
162 case orig.Kind == NameRef:
163 strs = append(strs, orig.Str)
164 case pe.Index != nil && vr.Kind == Indexed:
165 strs = vr.indexedKeys()
166 case pe.Index != nil && vr.Kind == Associative:
167 strs = slices.Sorted(maps.Keys(vr.Map))
168 case !vr.IsSet():
169 return "", fmt.Errorf("invalid indirect expansion")
170 case str == "":
171 return "", nil
172 default:
173 vr = cfg.Env.Get(str)
174 strs = append(strs, vr.String())
175 }
176 str = join(strs)
177 case pe.Width:
178 return "", fmt.Errorf("unsupported")
179 case pe.IsSet:
180 return "", fmt.Errorf("unsupported")
181 case pe.Slice != nil:
182 if callVarInd {
183 // The offset and length are in characters, not bytes.
184 rs := []rune(str)
185 slicePos := func(n int) int {
186 if n < 0 {
187 n = len(rs) + n
188 if n < 0 {
189 n = len(rs)
190 }
191 } else if n > len(rs) {
192 n = len(rs)
193 }
194 return n
195 }
196 if pe.Slice.Offset != nil {
197 rs = rs[slicePos(sliceOffset):]
198 }
199 if pe.Slice.Length != nil {
200 rs = rs[:slicePos(sliceLen)]
201 }
202 str = string(rs)
203 } // else, elems are already sliced
204 case pe.Repl != nil:
205 elems, err := cfg.replaceElems(pe.Repl, elems)
206 if err != nil {
207 return "", err
208 }
209 str = join(elems)
210 case pe.Exp != nil:
211 arg, err := Literal(cfg, pe.Exp.Word)
212 if err != nil {
213 return "", err
214 }
215 switch op := pe.Exp.Op; op {
216 case syntax.AlternateUnsetOrNull:
217 if str == "" {
218 break
219 }
220 fallthrough
221 case syntax.AlternateUnset:
222 if set {
223 str = arg
224 }
225 case syntax.DefaultUnset:
226 if set {
227 break
228 }
229 fallthrough
230 case syntax.DefaultUnsetOrNull:
231 if str == "" {
232 str = arg
233 }
234 case syntax.ErrorUnset:
235 if set {
236 break
237 }
238 fallthrough
239 case syntax.ErrorUnsetOrNull:
240 if str == "" {
241 return "", UnsetParameterError{
242 Node: pe,
243 Message: arg,
244 }
245 }
246 case syntax.AssignUnset:
247 if set {
248 break
249 }
250 fallthrough
251 case syntax.AssignUnsetOrNull:
252 if str == "" {
253 if err := cfg.assignElem(name, vr, index, arg); err != nil {
254 return "", err
255 }
256 str = arg
257 }
258 case syntax.RemSmallPrefix, syntax.RemLargePrefix,
259 syntax.RemSmallSuffix, syntax.RemLargeSuffix:
260 str = join(cfg.removePatternElems(op, arg, elems))
261 case syntax.UpperFirst, syntax.UpperAll,
262 syntax.LowerFirst, syntax.LowerAll:
263 str = join(cfg.caseConvElems(op, arg, elems))
264 case syntax.OtherParamOps:
265 switch arg {
266 case "Q":
267 str, err = syntax.Quote(str, syntax.LangBash)
268 if err != nil {
269 // Is this even possible? If a user runs into this panic,
270 // it's most likely a bug we need to fix.
271 panic(err)
272 }
273 case "E":
274 tail := str
275 var rns []rune
276 for tail != "" {
277 var rn rune
278 rn, _, tail, _ = strconv.UnquoteChar(tail, 0)
279 rns = append(rns, rn)
280 }
281 str = string(rns)
282 case "a":
283 // ${var@a} returns variable attribute flags.
284 // We use orig (before nameref resolve) for the attributes.
285 str = orig.Flags()
286 case "A":
287 // ${var@A} returns a declare statement that recreates the variable.
288 flags := orig.Flags()
289 quoted, err := syntax.Quote(str, syntax.LangBash)
290 if err != nil {
291 return "", err
292 }
293 if flags == "" {
294 str = fmt.Sprintf("%s=%s", name, quoted)
295 } else {
296 str = fmt.Sprintf("declare -%s %s=%s", flags, name, quoted)
297 }
298 case "P":
299 // TODO: implement prompt expansion (\u, \h, \w, etc.).
300 case "U":
301 str = strings.ToUpper(str)
302 case "u":
303 rs := []rune(str)
304 if len(rs) > 0 {
305 rs[0] = unicode.ToUpper(rs[0])
306 str = string(rs)
307 }
308 case "L":
309 str = strings.ToLower(str)
310 case "K", "k":
311 // TODO: implement, like @A but listing keys for assoc arrays.
312 default:
313 panic(fmt.Sprintf("unexpected @%s param expansion", arg))
314 }
315 }
316 }
317 return str, nil
318 }
319
320 func removePattern(str, pat string, fromEnd, shortest bool) string {
321 var mode pattern.Mode
322 if shortest {
323 mode |= pattern.Shortest
324 }
325 expr, err := pattern.Regexp(pat, mode)
326 if err != nil {
327 return str
328 }
329 switch {
330 case fromEnd && shortest:
331 // use .* to get the right-most shortest match
332 expr = ".*(" + expr + ")$"
333 case fromEnd:
334 // simple suffix
335 expr = "(" + expr + ")$"
336 default:
337 // simple prefix
338 expr = "^(" + expr + ")"
339 }
340 // no need to check error as Translate returns one
341 rx := regexp.MustCompile(expr)
342 if loc := rx.FindStringSubmatchIndex(str); loc != nil {
343 // remove the original pattern (the submatch)
344 str = str[:loc[2]] + str[loc[3]:]
345 }
346 return str
347 }
348
349 // The helpers below never modify elems in place, as it may alias a
350 // variable's list of elements.
351
352 // perElemOps applies pattern removal, replacement, or case conversion to
353 // each element, leaving them unchanged for any whole-expansion operator.
354 func (cfg *Config) perElemOps(pe *syntax.ParamExp, elems []string) ([]string, error) {
355 switch {
356 case pe.Repl != nil:
357 return cfg.replaceElems(pe.Repl, elems)
358 case pe.Exp != nil:
359 arg, err := Literal(cfg, pe.Exp.Word)
360 if err != nil {
361 return nil, err
362 }
363 switch op := pe.Exp.Op; op {
364 case syntax.RemSmallPrefix, syntax.RemLargePrefix,
365 syntax.RemSmallSuffix, syntax.RemLargeSuffix:
366 return cfg.removePatternElems(op, arg, elems), nil
367 case syntax.UpperFirst, syntax.UpperAll,
368 syntax.LowerFirst, syntax.LowerAll:
369 return cfg.caseConvElems(op, arg, elems), nil
370 }
371 }
372 return elems, nil
373 }
374
375 // replaceElems applies a ${var/pattern/repl} replacement to each element.
376 func (cfg *Config) replaceElems(repl *syntax.Replace, elems []string) ([]string, error) {
377 orig, err := Pattern(cfg, repl.Orig)
378 if err != nil {
379 return nil, err
380 }
381 if orig == "" {
382 return elems, nil // nothing to replace
383 }
384 with, err := Literal(cfg, repl.With)
385 if err != nil {
386 return nil, err
387 }
388 n := 1
389 if repl.All {
390 n = -1
391 }
392 out := make([]string, len(elems))
393 for i, elem := range elems {
394 locs := findAllIndex(orig, elem, n)
395 sb := cfg.strBuilder()
396 last := 0
397 for _, loc := range locs {
398 sb.WriteString(elem[last:loc[0]])
399 sb.WriteString(with)
400 last = loc[1]
401 }
402 sb.WriteString(elem[last:])
403 out[i] = sb.String()
404 }
405 return out, nil
406 }
407
408 // removePatternElems applies a pattern removal operator to each element.
409 func (cfg *Config) removePatternElems(op syntax.ParExpOperator, arg string, elems []string) []string {
410 suffix := op == syntax.RemSmallSuffix || op == syntax.RemLargeSuffix
411 small := op == syntax.RemSmallPrefix || op == syntax.RemSmallSuffix
412 out := make([]string, len(elems))
413 for i, elem := range elems {
414 out[i] = removePattern(elem, arg, suffix, small)
415 }
416 return out
417 }
418
419 // caseConvElems applies a case conversion operator to each element.
420 func (cfg *Config) caseConvElems(op syntax.ParExpOperator, arg string, elems []string) []string {
421 caseFunc := unicode.ToLower
422 if op == syntax.UpperFirst || op == syntax.UpperAll {
423 caseFunc = unicode.ToUpper
424 }
425 all := op == syntax.UpperAll || op == syntax.LowerAll
426
427 // empty string means '?'; nothing to do there
428 expr, err := pattern.Regexp(arg, 0)
429 if err != nil {
430 return elems
431 }
432 rx := regexp.MustCompile(expr)
433
434 out := make([]string, len(elems))
435 for i, elem := range elems {
436 rs := []rune(elem)
437 for ri, r := range rs {
438 if rx.MatchString(string(r)) {
439 rs[ri] = caseFunc(r)
440 }
441 if !all {
442 break // only the first character is considered
443 }
444 }
445 out[i] = string(rs)
446 }
447 return out
448 }
449
450 // varInd expands an indexed variable expansion like ${a[i]}, also reporting
451 // whether the resulting element is set, which may be false for missing array
452 // elements such as the holes in a sparse array.
453 func (cfg *Config) varInd(vr Variable, idx syntax.ArithmExpr) (string, bool, error) {
454 if idx == nil {
455 switch vr.Kind {
456 case Indexed:
457 // A bare $a is the element at index zero, which may be unset.
458 str, ok := vr.indexedVal(0)
459 return str, ok, nil
460 case Associative:
461 str, ok := vr.Map["0"]
462 return str, ok, nil
463 }
464 return vr.String(), vr.IsSet(), nil
465 }
466 switch vr.Kind {
467 case String:
468 n, err := Arithm(cfg, idx)
469 if err != nil {
470 return "", false, err
471 }
472 if n == 0 {
473 return vr.Str, vr.IsSet(), nil
474 }
475 case Indexed:
476 switch nodeLit(idx) {
477 case "*", "@":
478 return strings.Join(vr.List, " "), vr.IsSet(), nil
479 }
480 i, err := Arithm(cfg, idx)
481 if err != nil {
482 return "", false, err
483 }
484 if i < 0 {
485 // Negative indices count from one past the maximum index.
486 if i += internal.IndexedMax(vr.List, vr.Indexes) + 1; i < 0 {
487 return "", false, fmt.Errorf("negative array index")
488 }
489 }
490 if str, ok := vr.indexedVal(i); ok {
491 return str, true, nil
492 }
493 case Associative:
494 switch lit := nodeLit(idx); lit {
495 case "@", "*":
496 strs := slices.Sorted(maps.Values(vr.Map))
497 if lit == "*" {
498 return cfg.ifsJoin(strs), vr.IsSet(), nil
499 }
500 return strings.Join(strs, " "), vr.IsSet(), nil
501 }
502 val, err := Literal(cfg, idx.(*syntax.Word))
503 if err != nil {
504 return "", false, err
505 }
506 str, ok := vr.Map[val]
507 return str, ok, nil
508 }
509 return "", false, nil
510 }
511
512 // assignElem assigns a variable via an expansion like ${a=val} or
513 // ${a[i]=val}, setting a single element when the variable is an array or is
514 // indexed, like Bash. ${a[i]=val} on a whole scalar converts it to an array.
515 func (cfg *Config) assignElem(name string, vr Variable, idx syntax.ArithmExpr, val string) error {
516 wenv, ok := cfg.Env.(WriteEnviron)
517 if !ok {
518 return fmt.Errorf("environment is read-only")
519 }
520 arrayWise := false
521 switch nodeLit(idx) {
522 case "@", "*":
523 // ${a[@]=val} assigns the element at index zero.
524 arrayWise = true
525 idx = nil
526 }
527 if idx == nil && !arrayWise && vr.Kind != Indexed && vr.Kind != Associative {
528 // A plain scalar assignment like ${x=val}.
529 return wenv.Set(name, Variable{Set: true, Kind: String, Str: val})
530 }
531 switch vr.Kind {
532 case Associative:
533 key := "0"
534 if idx != nil {
535 var err error
536 if key, err = Literal(cfg, idx.(*syntax.Word)); err != nil {
537 return err
538 }
539 }
540 vr.Map = maps.Clone(vr.Map)
541 if vr.Map == nil {
542 vr.Map = make(map[string]string, 1)
543 }
544 vr.Map[key] = val
545 default: // assign a single indexed element
546 i := 0
547 if idx != nil {
548 var err error
549 if i, err = Arithm(cfg, idx); err != nil {
550 return err
551 }
552 if i < 0 {
553 // Negative indices count from one past the maximum index.
554 if i += internal.IndexedMax(vr.List, vr.Indexes) + 1; i < 0 {
555 return fmt.Errorf("negative array index")
556 }
557 }
558 }
559 list, indexes := slices.Clone(vr.List), slices.Clone(vr.Indexes)
560 if vr.Kind == String {
561 list, indexes = []string{vr.Str}, nil
562 }
563 list, indexes = internal.SetIndexedElem(list, indexes, i, val)
564 vr.Kind, vr.Str, vr.List, vr.Indexes = Indexed, "", list, indexes
565 }
566 vr.Set = true
567 return wenv.Set(name, vr)
568 }
569
570 func (cfg *Config) namesByPrefix(prefix string) []string {
571 var names []string
572 for name := range cfg.Env.Each {
573 if strings.HasPrefix(name, prefix) {
574 names = append(names, name)
575 }
576 }
577 slices.Sort(names)
578 return names
579 }