Skip to content

Commit

Permalink
retain initial spaces in string expressions (#243)
Browse files Browse the repository at this point in the history
Initially, any whitespaces after the opening quote in a string expression
are trimmed. This was meant only for indentations but it also removes
whitespaces that are just spaces. This commit changes that behavior
to retain initial spaces after the opening quote.
  • Loading branch information
nofun97 authored Jan 14, 2022
1 parent ec47b03 commit 4605098
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
8 changes: 8 additions & 0 deletions syntax/compile_xstr.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ var (
indentRE = regexp.MustCompile(`(\n[\t ]*)\z`)
firstIndentRE = regexp.MustCompile(`\A((\n[\t ]+)(?:\n)|(\n))`)
lastSpacesRE = regexp.MustCompile(`\n([ \t]*)\z`)
spaces = regexp.MustCompile(`\A[\t ]+`)
)

func (pc ParseContext) compileExpandableString(ctx context.Context, b ast.Branch, c ast.Children) (rel.Expr, error) {
Expand All @@ -25,6 +26,13 @@ func (pc ParseContext) compileExpandableString(ctx context.Context, b ast.Branch
parts := []interface{}{}

ws := quote[2:]

// retain initial spaces
if spaces.MatchString(ws) {
parts = append(parts, ws)
ws = ""
}

trim := ""
trimIndent := func(s string) {
s = ws + s
Expand Down
12 changes: 12 additions & 0 deletions syntax/parse_string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,18 @@ func TestXStringSimple(t *testing.T) {
AssertCodesEvalToSameValue(t, `"a42k3.142z" `, `$"a${6*7}k${//math.pi:.3f}z"`)
}

func TestXStringRetainInitialSpaces(t *testing.T) {
t.Parallel()

AssertCodesEvalToSameValue(t, `" " `, `$" " `)
AssertCodesEvalToSameValue(t, `" x" `, `$" x" `)
AssertCodesEvalToSameValue(t, `" abc" `, `$" ${'abc'}"`)
AssertCodesEvalToSameValue(t, `" abc"`, `$" ${$' abc'}"`)

// suppress empty line
AssertCodesEvalToSameValue(t, `""`, `$" ${''}"`)
}

func TestXStringBackquote(t *testing.T) {
t.Parallel()
AssertCodesEvalToSameValue(t, `"" `, "$``")
Expand Down

0 comments on commit 4605098

Please sign in to comment.