Skip to content

Commit

Permalink
syntax: fix whitespace on nested subshells (#874)
Browse files Browse the repository at this point in the history
we want white space on nested subshells if its in a single line since
its ambiguous, eg we want `( (` over `((`

this shouldn't be the case for multiple lines- fix the logic that adds
white space to only do so if the two subshells are in the same line

fixes #814
  • Loading branch information
riacataquian authored Jun 6, 2022
1 parent 4c7f3cb commit bd03166
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
15 changes: 13 additions & 2 deletions syntax/printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -1079,11 +1079,22 @@ func (p *Printer) command(cmd Command, redirs []*Redirect) (startRedirs int) {
p.ifClause(x, false)
case *Subshell:
p.WriteByte('(')
if len(x.Stmts) > 0 && startsWithLparen(x.Stmts[0]) {
stmts := x.Stmts
if len(stmts) > 0 && startsWithLparen(stmts[0]) {
p.wantSpace = spaceRequired
// Add a space between nested parentheses if we're printing them in a single line,
// to avoid the ambiguity between `((` and `( (`.
if (x.Lparen.Line() != stmts[0].Pos().Line() || len(stmts) > 1) && !p.singleLine {
p.wantSpace = spaceNotRequired

if p.minify {
p.mustNewline = true
}
}
} else {
p.wantSpace = spaceNotRequired
}

p.spacePad(stmtsPos(x.Stmts, x.Last))
p.nestedStmts(x.Stmts, x.Last, x.Rparen)
p.wantSpace = spaceNotRequired
Expand Down Expand Up @@ -1338,7 +1349,7 @@ func (p *Printer) stmtList(stmts []*Stmt, last []Comment) {
// statement.
p.comments(c)
}
if !p.minify || p.wantSpace == spaceRequired {
if p.mustNewline || !p.minify || p.wantSpace == spaceRequired {
p.newlines(pos)
}
p.line = pos.Line()
Expand Down
22 changes: 22 additions & 0 deletions syntax/printer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,28 @@ var printTests = []printCase{
"`declare`",
"$(declare)",
},
{
"(\n(foo >redir))",
"(\n\t(foo >redir)\n)",
},
{
"( (foo) )",
"( (foo))",
},
{
"( (foo); bar )",
"(\n\t(foo)\n\tbar\n)",
},
{
"( ((foo++)) )",
"( ((foo++)))",
},
{
"( ((foo++)); bar )",
"(\n\t((foo++))\n\tbar\n)",
},
samePrint("(\n\t((foo++))\n)"),
samePrint("(foo && bar)"),
}

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

0 comments on commit bd03166

Please sign in to comment.