Skip to content

Commit 2df1ac9

Browse files
committed
syntax: ValidName should return false on ""
An empty string isn't a valid name. For example, one cannot do any of the following: declare =bar echo ${} This wasn't a big problem in the parser, as it already knew whether or not it had a non-empty literal. But other users of ValidName, like interp, would get bugs because of the missing empty string check.
1 parent 5d72e7b commit 2df1ac9

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

syntax/parser.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1473,6 +1473,9 @@ func (p *Parser) backquoteEnd() bool {
14731473

14741474
// ValidName returns whether val is a valid name as per the POSIX spec.
14751475
func ValidName(val string) bool {
1476+
if val == "" {
1477+
return false
1478+
}
14761479
for i, r := range val {
14771480
switch {
14781481
case 'a' <= r && r <= 'z':

syntax/parser_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2110,3 +2110,28 @@ func TestParseStmtsStopAt(t *testing.T) {
21102110
t.Run(fmt.Sprintf("%02d", i), singleParse(p, c.in, want))
21112111
}
21122112
}
2113+
2114+
func TestValidName(t *testing.T) {
2115+
t.Parallel()
2116+
tests := []struct {
2117+
name string
2118+
in string
2119+
want bool
2120+
}{
2121+
{"Empty", "", false},
2122+
{"Simple", "foo", true},
2123+
{"MixedCase", "Foo", true},
2124+
{"Underscore", "_foo", true},
2125+
{"NumberPrefix", "3foo", false},
2126+
{"NumberSuffix", "foo3", true},
2127+
}
2128+
for _, tc := range tests {
2129+
t.Run(tc.name, func(t *testing.T) {
2130+
got := ValidName(tc.in)
2131+
if got != tc.want {
2132+
t.Fatalf("ValidName(%q) got %t, wanted %t",
2133+
tc.in, got, tc.want)
2134+
}
2135+
})
2136+
}
2137+
}

0 commit comments

Comments
 (0)