Skip to content

Commit

Permalink
syntax: ValidName should return false on ""
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mvdan committed Dec 6, 2018
1 parent 5d72e7b commit 2df1ac9
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
3 changes: 3 additions & 0 deletions syntax/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -1473,6 +1473,9 @@ func (p *Parser) backquoteEnd() bool {

// ValidName returns whether val is a valid name as per the POSIX spec.
func ValidName(val string) bool {
if val == "" {
return false
}
for i, r := range val {
switch {
case 'a' <= r && r <= 'z':
Expand Down
25 changes: 25 additions & 0 deletions syntax/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2110,3 +2110,28 @@ func TestParseStmtsStopAt(t *testing.T) {
t.Run(fmt.Sprintf("%02d", i), singleParse(p, c.in, want))
}
}

func TestValidName(t *testing.T) {
t.Parallel()
tests := []struct {
name string
in string
want bool
}{
{"Empty", "", false},
{"Simple", "foo", true},
{"MixedCase", "Foo", true},
{"Underscore", "_foo", true},
{"NumberPrefix", "3foo", false},
{"NumberSuffix", "foo3", true},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := ValidName(tc.in)
if got != tc.want {
t.Fatalf("ValidName(%q) got %t, wanted %t",
tc.in, got, tc.want)
}
})
}
}

0 comments on commit 2df1ac9

Please sign in to comment.