Skip to content

Commit

Permalink
Do not include hyphens in bash variable tokens
Browse files Browse the repository at this point in the history
In bash, `$FOO-bar` is the variable `$FOO` followed by `-bar`,
not a variable called `$FOO-bar`.
  • Loading branch information
wedaly committed Mar 22, 2024
1 parent dacb2cd commit 3ad462a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
11 changes: 6 additions & 5 deletions syntax/languages/bash.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,19 +44,20 @@ func BashParseFunc() parser.Func {
// From the GNU bash manual:
// "in is recognized as a reserved word if it is the third word of a case or select command.
// in and do are recognized as reserved words if they are the third word in a for command."
isLetter := func(r rune) bool { return unicode.IsLetter(r) || r == '_' || r == '-' }
isLetterOrDigit := func(r rune) bool { return isLetter(r) || unicode.IsDigit(r) }
isWordStart := func(r rune) bool { return unicode.IsLetter(r) || r == '_' }
isWordContinue := func(r rune) bool { return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' || r == '-' }
keywords := []string{
"if", "then", "elif", "else", "fi", "time",
"for", "in", "until", "while", "do", "done",
"case", "esac", "coproc", "select", "function",
}
parseKeyword := consumeSingleRuneLike(isLetter).
ThenMaybe(consumeRunesLike(isLetterOrDigit)).
parseKeyword := consumeSingleRuneLike(isWordStart).
ThenMaybe(consumeRunesLike(isWordContinue)).
MapWithInput(recognizeKeywordOrConsume(keywords))

isVariableNameRune := func(r rune) bool { return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' }
parseVariable := consumeString("$").
Then(consumeRunesLike(isLetterOrDigit).
Then(consumeRunesLike(isVariableNameRune).
Or(consumeLongestMatchingOption([]string{"!", "#", "$", "*", "-", "0", "?", "@", "-"}))).
Map(recognizeToken(bashTokenRoleVariable))

Expand Down
7 changes: 7 additions & 0 deletions syntax/languages/bash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,13 @@ esac`,
{Role: parser.TokenRoleKeyword, Text: `esac`},
},
},
{
name: "variable followed by hyphen",
text: "$FOO-bar",
expected: []TokenWithText{
{Role: bashTokenRoleVariable, Text: `$FOO`},
},
},
{
name: "variable brace expansion",
text: `${PATH:-}`,
Expand Down

0 comments on commit 3ad462a

Please sign in to comment.