Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

syntax: fix whitespace on nested subshells #874

Merged
merged 1 commit into from
Jun 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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