Skip to content

Commit

Permalink
syntax: simplify unset-or-null with null default to just unset
Browse files Browse the repository at this point in the history
If the default for an unset-or-null parameter expansion is null, the
or-null part of the expansion is redundant and can be removed. The
result is null on match either way.
  • Loading branch information
scop committed Apr 15, 2022
1 parent 43a1600 commit 5635541
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
5 changes: 5 additions & 0 deletions syntax/simplify.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import "bytes"
// Remove redundant quotes [[ "$var" == str ]]
// Merge negations with unary operators [[ ! -n $var ]]
// Use single quotes to shorten literals "\$foo"
// Remove redundant param expansion colons ${foo:-}
func Simplify(n Node) bool {
s := simplifier{}
Walk(n, s.visit)
Expand All @@ -37,6 +38,10 @@ func (s *simplifier) visit(node Node) bool {
x.Index = s.removeParensArithm(x.Index)
// don't inline params - same as above.

if x.Exp != nil && x.Exp.Op == DefaultUnsetOrNull && x.Exp.Word == nil {
s.modified = true
x.Exp.Op = DefaultUnset
}
if x.Slice == nil {
break
}
Expand Down
4 changes: 4 additions & 0 deletions syntax/simplify_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,10 @@ var simplifyTests = [...]simplifyTest{
{"\"fo\\`o\"", "'fo`o'"},
noSimple(`fo"o"bar`),
noSimple(`foo""bar`),

// param expansions
{`${foo:-}`, `${foo-}`},
noSimple(`${foo:-bar}`),
}

func TestSimplify(t *testing.T) {
Expand Down

0 comments on commit 5635541

Please sign in to comment.