Skip to content

Commit bd03166

Browse files
authored
syntax: fix whitespace on nested subshells (#874)
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
1 parent 4c7f3cb commit bd03166

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

syntax/printer.go

+13-2
Original file line numberDiff line numberDiff line change
@@ -1079,11 +1079,22 @@ func (p *Printer) command(cmd Command, redirs []*Redirect) (startRedirs int) {
10791079
p.ifClause(x, false)
10801080
case *Subshell:
10811081
p.WriteByte('(')
1082-
if len(x.Stmts) > 0 && startsWithLparen(x.Stmts[0]) {
1082+
stmts := x.Stmts
1083+
if len(stmts) > 0 && startsWithLparen(stmts[0]) {
10831084
p.wantSpace = spaceRequired
1085+
// Add a space between nested parentheses if we're printing them in a single line,
1086+
// to avoid the ambiguity between `((` and `( (`.
1087+
if (x.Lparen.Line() != stmts[0].Pos().Line() || len(stmts) > 1) && !p.singleLine {
1088+
p.wantSpace = spaceNotRequired
1089+
1090+
if p.minify {
1091+
p.mustNewline = true
1092+
}
1093+
}
10841094
} else {
10851095
p.wantSpace = spaceNotRequired
10861096
}
1097+
10871098
p.spacePad(stmtsPos(x.Stmts, x.Last))
10881099
p.nestedStmts(x.Stmts, x.Last, x.Rparen)
10891100
p.wantSpace = spaceNotRequired
@@ -1338,7 +1349,7 @@ func (p *Printer) stmtList(stmts []*Stmt, last []Comment) {
13381349
// statement.
13391350
p.comments(c)
13401351
}
1341-
if !p.minify || p.wantSpace == spaceRequired {
1352+
if p.mustNewline || !p.minify || p.wantSpace == spaceRequired {
13421353
p.newlines(pos)
13431354
}
13441355
p.line = pos.Line()

syntax/printer_test.go

+22
Original file line numberDiff line numberDiff line change
@@ -616,6 +616,28 @@ var printTests = []printCase{
616616
"`declare`",
617617
"$(declare)",
618618
},
619+
{
620+
"(\n(foo >redir))",
621+
"(\n\t(foo >redir)\n)",
622+
},
623+
{
624+
"( (foo) )",
625+
"( (foo))",
626+
},
627+
{
628+
"( (foo); bar )",
629+
"(\n\t(foo)\n\tbar\n)",
630+
},
631+
{
632+
"( ((foo++)) )",
633+
"( ((foo++)))",
634+
},
635+
{
636+
"( ((foo++)); bar )",
637+
"(\n\t((foo++))\n\tbar\n)",
638+
},
639+
samePrint("(\n\t((foo++))\n)"),
640+
samePrint("(foo && bar)"),
619641
}
620642

621643
func TestPrintWeirdFormat(t *testing.T) {

0 commit comments

Comments
 (0)