Debian Codegraph @

syntax/printer.go

raw
1 // Copyright (c) 2016, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 package syntax
5
6 import (
7 "bufio"
8 "bytes"
9 "fmt"
10 "io"
11 "strings"
12 "text/tabwriter"
13 "unicode"
14
15 "mvdan.cc/sh/v3/fileutil"
16 )
17
18 // PrinterOption is a function which can be passed to NewPrinter
19 // to alter its behavior. To apply option to existing Printer
20 // call it directly, for example KeepPadding(true)(printer).
21 type PrinterOption func(*Printer)
22
23 // Indent sets the number of spaces used for indentation. If set to 0,
24 // tabs will be used instead.
25 func Indent(spaces uint) PrinterOption {
26 return func(p *Printer) { p.indentSpaces = spaces }
27 }
28
29 // BinaryNextLine will make binary operators appear on the next line
30 // when a binary command, such as a pipe, spans multiple lines. A
31 // backslash will be used.
32 func BinaryNextLine(enabled bool) PrinterOption {
33 return func(p *Printer) { p.binNextLine = enabled }
34 }
35
36 // SwitchCaseIndent will make switch cases be indented. As such, switch
37 // case bodies will be two levels deeper than the switch itself.
38 func SwitchCaseIndent(enabled bool) PrinterOption {
39 return func(p *Printer) { p.swtCaseIndent = enabled }
40 }
41
42 // TODO(v4): consider turning this into a "space all operators" option, to also
43 // allow foo=( bar baz ), (( x + y )), and so on.
44
45 // SpaceRedirects will put a space after most redirection operators. The
46 // exceptions are '>&', '<&', '>(', and '<('.
47 func SpaceRedirects(enabled bool) PrinterOption {
48 return func(p *Printer) { p.spaceRedirects = enabled }
49 }
50
51 // KeepPadding will keep most nodes and tokens in the same column that
52 // they were in the original source. This allows the user to decide how
53 // to align and pad their code with spaces.
54 //
55 // Note that this feature is best-effort and will only keep the
56 // alignment stable, so it may need some human help the first time it is
57 // run.
58 //
59 // Deprecated: this formatting option is flawed and buggy, and often does
60 // not result in what the user wants when the code gets complex enough.
61 // The next major version, v4, will remove this feature entirely.
62 // See: https://github.com/mvdan/sh/issues/658
63 func KeepPadding(enabled bool) PrinterOption {
64 return func(p *Printer) {
65 if enabled && !p.keepPadding {
66 // Enable the flag, and set up the writer wrapper.
67 p.keepPadding = true
68 p.cols.Writer = p.w.(*bufio.Writer)
69 p.w = &p.cols
70
71 } else if !enabled && p.keepPadding {
72 // Ensure we reset the state to that of NewPrinter.
73 p.keepPadding = false
74 p.w = p.cols.Writer
75 p.cols = colCounter{}
76 }
77 }
78 }
79
80 // Minify will print programs in a way to save the most bytes possible.
81 // For example, indentation and comments are skipped, and extra
82 // whitespace is avoided when possible.
83 func Minify(enabled bool) PrinterOption {
84 return func(p *Printer) { p.minify = enabled }
85 }
86
87 // SingleLine will attempt to print programs in one line. For example, lists of
88 // commands or nested blocks do not use newlines in this mode. Note that some
89 // newlines must still appear, such as those following comments or around
90 // here-documents.
91 //
92 // Print's trailing newline when given a [*File] is not affected by this option.
93 func SingleLine(enabled bool) PrinterOption {
94 return func(p *Printer) { p.singleLine = enabled }
95 }
96
97 // FunctionNextLine will place a function's opening braces on the next line.
98 func FunctionNextLine(enabled bool) PrinterOption {
99 return func(p *Printer) { p.funcNextLine = enabled }
100 }
101
102 // NewPrinter allocates a new Printer and applies any number of options.
103 func NewPrinter(opts ...PrinterOption) *Printer {
104 p := &Printer{
105 w: bufio.NewWriter(nil),
106 tabWriter: new(tabwriter.Writer),
107 }
108 for _, opt := range opts {
109 opt(p)
110 }
111 return p
112 }
113
114 // Print "pretty-prints" the given syntax tree node to the given writer. Writes
115 // to w are buffered.
116 //
117 // The node types supported at the moment are [*File], [*Stmt], [*Word], [*Assign], any
118 // [Command] node, and any WordPart node. A trailing newline will only be printed
119 // when a [*File] is used.
120 func (p *Printer) Print(w io.Writer, node Node) error {
121 p.reset()
122
123 if p.minify && p.singleLine {
124 return fmt.Errorf("Minify and SingleLine together are not supported yet; please file an issue describing your use case: https://github.com/mvdan/sh/issues")
125 }
126
127 // TODO: consider adding a raw mode to skip the tab writer, much like in
128 // go/printer.
129 twmode := tabwriter.DiscardEmptyColumns | tabwriter.StripEscape
130 tabwidth := 8
131 if p.indentSpaces == 0 {
132 // indenting with tabs
133 twmode |= tabwriter.TabIndent
134 } else {
135 // indenting with spaces
136 tabwidth = int(p.indentSpaces)
137 }
138 p.tabWriter.Init(w, 0, tabwidth, 1, ' ', twmode)
139 w = p.tabWriter
140
141 p.w.Reset(w)
142 switch node := node.(type) {
143 case *File:
144 p.stmtList(node.Stmts, node.Last)
145 p.newline(Pos{})
146 case *Stmt:
147 p.stmtList([]*Stmt{node}, nil)
148 case Command:
149 p.command(node, nil)
150 case *Word:
151 p.line = node.Pos().Line()
152 p.word(node)
153 case WordPart:
154 p.line = node.Pos().Line()
155 p.wordPart(node, nil)
156 case *Assign:
157 p.line = node.Pos().Line()
158 p.assigns([]*Assign{node})
159 default:
160 return fmt.Errorf("unsupported node type: %T", node)
161 }
162 p.flushHeredocs()
163 p.flushComments()
164
165 // flush the writers
166 if err := p.w.Flush(); err != nil {
167 return err
168 }
169 if tw, _ := w.(*tabwriter.Writer); tw != nil {
170 if err := tw.Flush(); err != nil {
171 return err
172 }
173 }
174 return nil
175 }
176
177 type bufWriter interface {
178 Write([]byte) (int, error)
179 WriteString(string) (int, error)
180 WriteByte(byte) error
181 Reset(io.Writer)
182 Flush() error
183 }
184
185 type colCounter struct {
186 *bufio.Writer
187 column int
188 lineStart bool
189 }
190
191 func (c *colCounter) addByte(b byte) {
192 switch b {
193 case '\n':
194 c.column = 0
195 c.lineStart = true
196 case '\t', ' ', tabwriter.Escape:
197 default:
198 c.lineStart = false
199 }
200 c.column++
201 }
202
203 func (c *colCounter) WriteByte(b byte) error {
204 c.addByte(b)
205 return c.Writer.WriteByte(b)
206 }
207
208 func (c *colCounter) WriteString(s string) (int, error) {
209 for _, b := range []byte(s) {
210 c.addByte(b)
211 }
212 return c.Writer.WriteString(s)
213 }
214
215 func (c *colCounter) Reset(w io.Writer) {
216 c.column = 1
217 c.lineStart = true
218 c.Writer.Reset(w)
219 }
220
221 // Printer holds the internal state of the printing mechanism of a
222 // program.
223 type Printer struct {
224 w bufWriter
225 tabWriter *tabwriter.Writer
226 cols colCounter // used for [KeepPadding]
227
228 indentSpaces uint
229 binNextLine bool
230 swtCaseIndent bool
231 spaceRedirects bool
232 keepPadding bool
233 minify bool
234 singleLine bool
235 funcNextLine bool
236
237 wantSpace wantSpaceState // whether space is required or has been written
238
239 wantNewline bool // newline is wanted for pretty-printing; ignored by singleLine; ignored by singleLine
240 mustNewline bool // newline is required to keep shell syntax valid
241 wroteSemi bool // wrote ';' for the current statement
242
243 // pendingComments are any comments in the current line or statement
244 // that we have yet to print. This is useful because that way, we can
245 // ensure that all comments are written immediately before a newline.
246 // Otherwise, in some edge cases we might wrongly place words after a
247 // comment in the same line, breaking programs.
248 pendingComments []Comment
249
250 // firstLine means we are still writing the first line
251 firstLine bool
252 // line is the current line number
253 line uint
254
255 // lastLevel is the last level of indentation that was used.
256 lastLevel uint
257 // level is the current level of indentation.
258 level uint
259 // levelIncs records which indentation level increments actually
260 // took place, to revert them once their section ends.
261 levelIncs []bool
262
263 nestedBinary bool
264
265 // pendingHdocs is the list of pending heredocs to write.
266 pendingHdocs []*Redirect
267
268 // used when printing <<- heredocs with tab indentation
269 tabsPrinter *Printer
270 }
271
272 func (p *Printer) reset() {
273 p.wantSpace = spaceWritten
274 p.wantNewline, p.mustNewline = false, false
275 p.pendingComments = p.pendingComments[:0]
276
277 // minification uses its own newline logic
278 p.firstLine = !p.minify
279 p.line = 0
280
281 p.lastLevel, p.level = 0, 0
282 p.levelIncs = p.levelIncs[:0]
283 p.nestedBinary = false
284 p.pendingHdocs = p.pendingHdocs[:0]
285 }
286
287 func (p *Printer) spaces(n uint) {
288 for range n {
289 p.w.WriteByte(' ')
290 }
291 }
292
293 func (p *Printer) space() {
294 p.w.WriteByte(' ')
295 p.wantSpace = spaceWritten
296 }
297
298 func (p *Printer) spacePad(pos Pos) {
299 if p.cols.lineStart && p.indentSpaces == 0 {
300 // Never add padding at the start of a line unless we are indenting
301 // with spaces, since this may result in mixing of spaces and tabs.
302 return
303 }
304 if p.wantSpace == spaceRequired {
305 p.w.WriteByte(' ')
306 p.wantSpace = spaceWritten
307 }
308 for p.cols.column > 0 && p.cols.column < int(pos.Col()) {
309 p.w.WriteByte(' ')
310 }
311 }
312
313 // wantsNewline reports whether we want to print at least one newline before
314 // printing a node at a given position. A zero position can be given to simply
315 // tell if we want a newline following what's just been printed.
316 func (p *Printer) wantsNewline(pos Pos, escapingNewline bool) bool {
317 if p.mustNewline {
318 // We must have a newline here.
319 return true
320 }
321 if p.singleLine && len(p.pendingComments) == 0 {
322 // The newline is optional, and singleLine skips it.
323 // Don't skip if there are any pending comments,
324 // as that might move them further down to the wrong place.
325 return false
326 }
327 if escapingNewline && p.minify {
328 return false
329 }
330 // The newline is optional, and we want it via either wantNewline or via
331 // the position's line.
332 return p.wantNewline || pos.Line() > p.line
333 }
334
335 func (p *Printer) bslashNewl() {
336 if p.wantSpace == spaceRequired {
337 p.space()
338 }
339 p.w.WriteString("\\\n")
340 p.line++
341 p.indent()
342 }
343
344 func (p *Printer) spacedString(s string, pos Pos) {
345 p.spacePad(pos)
346 p.w.WriteString(s)
347 p.wantSpace = spaceRequired
348 }
349
350 func (p *Printer) spacedToken(s string, pos Pos) {
351 if p.minify {
352 p.w.WriteString(s)
353 p.wantSpace = spaceNotRequired
354 return
355 }
356 p.spacePad(pos)
357 p.w.WriteString(s)
358 p.wantSpace = spaceRequired
359 }
360
361 func (p *Printer) semiOrNewl(s string, pos Pos) {
362 if p.wantsNewline(Pos{}, false) || len(p.pendingHdocs) > 0 {
363 p.newline(pos)
364 p.indent()
365 } else {
366 if !p.wroteSemi {
367 p.w.WriteByte(';')
368 }
369 if !p.minify {
370 p.space()
371 }
372 p.advanceLine(pos.Line())
373 }
374 p.w.WriteString(s)
375 p.wantSpace = spaceRequired
376 }
377
378 func (p *Printer) writeLit(s string) {
379 // If p.tabWriter is nil, this is the nested printer being used to print
380 // <<- heredoc bodies, so the parent printer will add the escape bytes
381 // later.
382 if p.tabWriter != nil && strings.Contains(s, "\t") {
383 p.w.WriteByte(tabwriter.Escape)
384 defer p.w.WriteByte(tabwriter.Escape)
385 }
386 p.w.WriteString(s)
387 }
388
389 func (p *Printer) incLevel() {
390 inc := false
391 if p.level <= p.lastLevel || len(p.levelIncs) == 0 {
392 p.level++
393 inc = true
394 } else if last := &p.levelIncs[len(p.levelIncs)-1]; *last {
395 *last = false
396 inc = true
397 }
398 p.levelIncs = append(p.levelIncs, inc)
399 }
400
401 func (p *Printer) decLevel() {
402 if p.levelIncs[len(p.levelIncs)-1] {
403 p.level--
404 }
405 p.levelIncs = p.levelIncs[:len(p.levelIncs)-1]
406 }
407
408 func (p *Printer) indent() {
409 if p.minify {
410 return
411 }
412 p.lastLevel = p.level
413 switch {
414 case p.level == 0:
415 case p.indentSpaces == 0:
416 p.w.WriteByte(tabwriter.Escape)
417 for i := uint(0); i < p.level; i++ {
418 p.w.WriteByte('\t')
419 }
420 p.w.WriteByte(tabwriter.Escape)
421 default:
422 p.spaces(p.indentSpaces * p.level)
423 }
424 }
425
426 // TODO(mvdan): add an indent call at the end of newline?
427
428 // newline prints one newline and advances p.line to pos.Line().
429 func (p *Printer) newline(pos Pos) {
430 p.flushHeredocs()
431 p.flushComments()
432 p.w.WriteByte('\n')
433 p.wantSpace = spaceWritten
434 p.wantNewline, p.mustNewline = false, false
435 p.advanceLine(pos.Line())
436 }
437
438 func (p *Printer) advanceLine(line uint) {
439 p.line = max(p.line, line)
440 }
441
442 func (p *Printer) flushHeredocs() {
443 if len(p.pendingHdocs) == 0 {
444 return
445 }
446 hdocs := p.pendingHdocs
447 p.pendingHdocs = p.pendingHdocs[:0]
448 coms := p.pendingComments
449 p.pendingComments = nil
450 if len(coms) > 0 {
451 c := coms[0]
452 if c.Pos().Line() == p.line {
453 p.pendingComments = append(p.pendingComments, c)
454 p.flushComments()
455 coms = coms[1:]
456 }
457 }
458
459 // Reuse the last indentation level, as
460 // indentation levels are usually changed before
461 // newlines are printed along with their
462 // subsequent indentation characters.
463 newLevel := p.level
464 p.level = p.lastLevel
465
466 for _, r := range hdocs {
467 p.line++
468 p.w.WriteByte('\n')
469 p.wantSpace = spaceWritten
470 p.wantNewline, p.mustNewline = false, false
471 if r.Op == DashHdoc && p.indentSpaces == 0 && !p.minify {
472 if r.Hdoc != nil {
473 extra := extraIndenter{
474 bufWriter: p.w,
475 baseIndent: int(p.level + 1),
476 firstIndent: -1,
477 }
478 p.tabsPrinter = &Printer{
479 w: &extra,
480
481 // The options need to persist.
482 indentSpaces: p.indentSpaces,
483 binNextLine: p.binNextLine,
484 swtCaseIndent: p.swtCaseIndent,
485 spaceRedirects: p.spaceRedirects,
486 keepPadding: p.keepPadding,
487 minify: p.minify,
488 funcNextLine: p.funcNextLine,
489
490 line: r.Hdoc.Pos().Line(),
491 }
492 p.tabsPrinter.wordParts(r.Hdoc.Parts, true)
493 }
494 p.indent()
495 } else if r.Hdoc != nil {
496 p.wordParts(r.Hdoc.Parts, true)
497 }
498 p.unquotedWord(r.Word)
499 if r.Hdoc != nil {
500 // Overwrite p.line, since printing r.Word again can set
501 // p.line to the beginning of the heredoc again.
502 p.advanceLine(r.Hdoc.End().Line())
503 }
504 p.wantSpace = spaceNotRequired
505 }
506 p.level = newLevel
507 p.pendingComments = coms
508 p.mustNewline = true
509 }
510
511 // newline prints between zero and two newlines.
512 // If any newlines are printed, it advances p.line to pos.Line().
513 func (p *Printer) newlines(pos Pos) {
514 if p.firstLine && len(p.pendingComments) == 0 {
515 p.firstLine = false
516 return // no empty lines at the top
517 }
518 if !p.wantsNewline(pos, false) {
519 return
520 }
521 p.flushHeredocs()
522 p.flushComments()
523 p.w.WriteByte('\n')
524 p.wantSpace = spaceWritten
525 p.wantNewline, p.mustNewline = false, false
526
527 l := pos.Line()
528 if l > p.line+1 && !p.minify {
529 p.w.WriteByte('\n') // preserve single empty lines
530 }
531 p.advanceLine(l)
532 p.indent()
533 }
534
535 func (p *Printer) rightParen(pos Pos) {
536 if len(p.pendingHdocs) > 0 || !p.minify {
537 p.newlines(pos)
538 }
539 p.w.WriteByte(')')
540 p.wantSpace = spaceRequired
541 }
542
543 // closingParen prints a closing parenthesis at closePos, separating it from a
544 // preceding closing parenthesis on the same line to mirror the `( (` spacing
545 // that startsWithLparen adds to the matching opening parenthesis.
546 func (p *Printer) closingParen(stmts []*Stmt, last []Comment, openPos, closePos Pos) {
547 p.wantSpace = spaceNotRequired
548 if len(last) == 0 && len(stmts) == 1 && endsWithRparen(stmts[0]) &&
549 (p.singleLine || openPos.Line() == closePos.Line()) {
550 p.wantSpace = spaceRequired
551 }
552 p.spacePad(closePos)
553 p.rightParen(closePos)
554 }
555
556 func (p *Printer) semiRsrv(s string, pos Pos) {
557 if p.wantsNewline(pos, false) {
558 p.newlines(pos)
559 } else {
560 if !p.wroteSemi {
561 p.w.WriteByte(';')
562 }
563 if !p.minify {
564 p.spacePad(pos)
565 }
566 }
567 p.w.WriteString(s)
568 p.wantSpace = spaceRequired
569 }
570
571 func (p *Printer) flushComments() {
572 if len(p.pendingComments) > 0 {
573 // Flush any pending heredocs first. Otherwise, the comments would
574 // become part of a heredoc body. flushHeredocs may print and consume
575 // an inline comment, so range over pendingComments only after flushing,
576 // not over a stale copy that would reprint it after the heredoc.
577 p.flushHeredocs()
578 }
579 for i, c := range p.pendingComments {
580 p.firstLine = false
581 // We can't call any of the newline methods, as they call this
582 // function and we'd recurse forever.
583 cline := c.Hash.Line()
584 switch {
585 case p.mustNewline, i > 0, cline > p.line && p.line > 0:
586 p.w.WriteByte('\n')
587 if cline > p.line+1 {
588 p.w.WriteByte('\n')
589 }
590 p.indent()
591 p.wantSpace = spaceWritten
592 p.spacePad(c.Pos())
593 case p.wantSpace == spaceRequired:
594 if p.keepPadding {
595 p.spacePad(c.Pos())
596 } else {
597 p.w.WriteByte('\t')
598 }
599 case p.wantSpace != spaceWritten:
600 p.space()
601 }
602 // don't go back one line, which may happen in some edge cases
603 p.advanceLine(cline)
604 p.w.WriteByte('#')
605 p.writeLit(strings.TrimRightFunc(c.Text, unicode.IsSpace))
606 p.wantNewline = true
607 p.mustNewline = true
608 }
609 p.pendingComments = nil
610 }
611
612 func (p *Printer) comments(comments ...Comment) {
613 if p.minify {
614 for _, c := range comments {
615 if fileutil.Shebang([]byte("#"+c.Text)) != "" && c.Hash.Col() == 1 && c.Hash.Line() == 1 {
616 p.w.WriteString(strings.TrimRightFunc("#"+c.Text, unicode.IsSpace))
617 p.w.WriteString("\n")
618 p.line++
619 }
620 }
621 return
622 }
623 p.pendingComments = append(p.pendingComments, comments...)
624 }
625
626 func (p *Printer) wordParts(wps []WordPart, quoted bool) {
627 // We disallow unquoted escaped newlines between word parts below.
628 // However, we want to allow a leading escaped newline for cases such as:
629 //
630 // foo <<< \
631 // "bar baz"
632 if !quoted && !p.singleLine && wps[0].Pos().Line() > p.line {
633 p.bslashNewl()
634 }
635 for i, wp := range wps {
636 var next WordPart
637 if i+1 < len(wps) {
638 next = wps[i+1]
639 }
640 // Keep escaped newlines separating word parts when quoted.
641 // Note that those escaped newlines don't cause indentaiton.
642 // When not quoted, we strip them out consistently,
643 // because attempting to keep them would prevent indentation.
644 // Can't use p.wantsNewline here, since this is only about
645 // escaped newlines.
646 for quoted && !p.singleLine && wp.Pos().Line() > p.line {
647 p.w.WriteString("\\\n")
648 p.line++
649 }
650 p.wordPart(wp, next)
651 p.advanceLine(wp.End().Line())
652 }
653 }
654
655 func (p *Printer) wordPart(wp, next WordPart) {
656 switch wp := wp.(type) {
657 case *Lit:
658 p.writeLit(wp.Value)
659 // An odd number of trailing backslashes would escape whatever
660 // follows, such as the newline ending a file; escape the last
661 // backslash to keep the literal value intact. Parsed source can
662 // only hit this case via a lone backslash at the end of a file.
663 if n := len(wp.Value) - len(strings.TrimRight(wp.Value, `\`)); n%2 == 1 {
664 p.w.WriteByte('\\')
665 }
666 case *SglQuoted:
667 if wp.Dollar {
668 p.w.WriteByte('$')
669 }
670 p.w.WriteByte('\'')
671 p.writeLit(wp.Value)
672 p.w.WriteByte('\'')
673 p.advanceLine(wp.End().Line())
674 case *DblQuoted:
675 p.dblQuoted(wp)
676 case *CmdSubst:
677 p.advanceLine(wp.Pos().Line())
678 p.cmdSubst(wp)
679 case *ParamExp:
680 litCont := ";"
681 if nextLit, ok := next.(*Lit); ok && nextLit.Value != "" {
682 litCont = nextLit.Value[:1]
683 }
684 if p.minify && !wp.Short && wp.simple() {
685 name := wp.Param.Value
686 switch {
687 case len(name) > 1 && !ValidName(name): // ${10}
688 case ValidName(name + litCont): // ${var}cont
689 default:
690 x2 := *wp
691 x2.Short = true
692 p.paramExp(&x2)
693 return
694 }
695 }
696 p.paramExp(wp)
697 case *ArithmExp:
698 p.w.WriteString("$((")
699 if wp.Unsigned {
700 p.w.WriteString("# ")
701 }
702 p.arithmExpr(wp.X, false, false)
703 p.w.WriteString("))")
704 case *ExtGlob:
705 p.w.WriteString(wp.Op.String())
706 p.writeLit(wp.Pattern.Value)
707 p.w.WriteByte(')')
708 case *ProcSubst:
709 // avoid conflict with << and others
710 if p.wantSpace == spaceRequired {
711 p.space()
712 }
713 p.w.WriteString(wp.Op.String())
714 p.nestedStmts(wp.Stmts, wp.Last, wp.Rparen)
715 p.rightParen(wp.Rparen)
716 }
717 }
718
719 func (p *Printer) dblQuoted(dq *DblQuoted) {
720 if dq.Dollar {
721 p.w.WriteByte('$')
722 }
723 p.w.WriteByte('"')
724 if len(dq.Parts) > 0 {
725 p.wordParts(dq.Parts, true)
726 }
727 // Add any trailing escaped newlines.
728 for p.line < dq.Right.Line() {
729 p.w.WriteString("\\\n")
730 p.line++
731 }
732 p.w.WriteByte('"')
733 }
734
735 func (p *Printer) wroteIndex(index ArithmExpr) bool {
736 if index == nil {
737 return false
738 }
739 p.w.WriteByte('[')
740 // Note that e.g. foo[1,3]=$bar in Zsh does not allow any spaces around the comma,
741 // as that breaks the assignment word.
742 binary, ok := index.(*BinaryArithm)
743 compact := ok && binary.Op == Comma
744 p.arithmExpr(index, compact, false)
745 p.w.WriteByte(']')
746 return true
747 }
748
749 func (p *Printer) paramExp(pe *ParamExp) {
750 if pe.nakedIndex() { // arr[x]
751 p.writeLit(pe.Param.Value)
752 p.wroteIndex(pe.Index)
753 return
754 }
755 p.w.WriteByte('$')
756 if !pe.Short {
757 p.w.WriteByte('{')
758 }
759 if pe.Flags != nil {
760 p.w.WriteByte('(')
761 p.writeLit(pe.Flags.Value)
762 p.w.WriteByte(')')
763 }
764 switch {
765 case pe.Length:
766 p.w.WriteByte('#')
767 case pe.Width:
768 p.w.WriteByte('%')
769 case pe.IsSet:
770 p.w.WriteByte('+')
771 case pe.Excl:
772 p.w.WriteByte('!')
773 }
774 for _, pre := range [...]struct {
775 c byte
776 state OptState
777 }{
778 {'=', pe.Split},
779 {'~', pe.GlobSubst},
780 {'^', pe.RcExpand},
781 } {
782 if pre.state == OptUnset {
783 continue
784 }
785 p.w.WriteByte(pre.c)
786 if pre.state == OptOff {
787 p.w.WriteByte(pre.c)
788 }
789 }
790 switch {
791 case pe.Param != nil:
792 p.writeLit(pe.Param.Value)
793 case pe.NestedParam != nil:
794 // Note that Zsh supports ${${nested}} but not ${$nested},
795 // so we need to avoid that simplification here.
796 saved := p.minify
797 p.minify = false
798 p.wordPart(pe.NestedParam, nil)
799 p.minify = saved
800 }
801 p.wroteIndex(pe.Index)
802 switch {
803 case len(pe.Modifiers) > 0:
804 for _, lit := range pe.Modifiers {
805 p.w.WriteByte(':')
806 p.w.WriteString(lit.Value)
807 }
808 case pe.Slice != nil:
809 p.w.WriteByte(':')
810 p.arithmExpr(pe.Slice.Offset, true, true)
811 if pe.Slice.Length != nil {
812 p.w.WriteByte(':')
813 p.arithmExpr(pe.Slice.Length, true, false)
814 }
815 case pe.Repl != nil:
816 if pe.Repl.All {
817 p.w.WriteByte('/')
818 }
819 p.w.WriteByte('/')
820 if pe.Repl.Orig != nil {
821 p.word(pe.Repl.Orig)
822 }
823 p.w.WriteByte('/')
824 if pe.Repl.With != nil {
825 p.word(pe.Repl.With)
826 }
827 case pe.Names != 0:
828 p.writeLit(pe.Names.String())
829 case pe.Exp != nil:
830 p.w.WriteString(pe.Exp.Op.String())
831 if pe.Exp.Word != nil {
832 p.word(pe.Exp.Word)
833 }
834 }
835 if !pe.Short {
836 p.w.WriteByte('}')
837 }
838 }
839
840 func (p *Printer) cmdSubst(cs *CmdSubst) {
841 switch {
842 case cs.TempFile:
843 p.w.WriteString("${")
844 p.wantSpace = spaceRequired
845 p.nestedStmts(cs.Stmts, cs.Last, cs.Right)
846 p.wantSpace = spaceNotRequired
847 p.semiRsrv("}", cs.Right)
848 case cs.ReplyVar:
849 p.w.WriteString("${|")
850 p.nestedStmts(cs.Stmts, cs.Last, cs.Right)
851 p.wantSpace = spaceNotRequired
852 p.semiRsrv("}", cs.Right)
853 // Special case: `# inline comment`
854 case cs.Backquotes && len(cs.Stmts) == 0 &&
855 len(cs.Last) == 1 && cs.Right.Line() == p.line:
856 p.w.WriteString("`#")
857 p.w.WriteString(cs.Last[0].Text)
858 p.w.WriteString("`")
859 default:
860 p.w.WriteString("$(")
861 if len(cs.Stmts) > 0 && startsWithLparen(cs.Stmts[0]) {
862 p.wantSpace = spaceRequired
863 } else {
864 p.wantSpace = spaceNotRequired
865 }
866 p.nestedStmts(cs.Stmts, cs.Last, cs.Right)
867 p.closingParen(cs.Stmts, cs.Last, cs.Left, cs.Right)
868 }
869 }
870
871 func (p *Printer) loop(loop Loop) {
872 switch loop := loop.(type) {
873 case *WordIter:
874 p.writeLit(loop.Name.Value)
875 if loop.InPos.IsValid() {
876 p.spacedString(" in", Pos{})
877 p.wordJoin(loop.Items)
878 }
879 case *CStyleLoop:
880 p.w.WriteString("((")
881 if loop.Init == nil {
882 p.space()
883 }
884 p.arithmExpr(loop.Init, false, false)
885 p.w.WriteString("; ")
886 p.arithmExpr(loop.Cond, false, false)
887 p.w.WriteString("; ")
888 p.arithmExpr(loop.Post, false, false)
889 p.w.WriteString("))")
890 }
891 }
892
893 func (p *Printer) arithmExpr(expr ArithmExpr, compact, spacePlusMinus bool) {
894 if p.minify {
895 compact = true
896 }
897 p.arithmExprRecurse(expr, compact, spacePlusMinus)
898 }
899
900 func (p *Printer) arithmExprRecurse(expr ArithmExpr, compact, spacePlusMinus bool) {
901 switch expr := expr.(type) {
902 case *Word:
903 p.word(expr)
904 case *BinaryArithm:
905 if compact {
906 p.arithmExprRecurse(expr.X, compact, spacePlusMinus)
907 p.w.WriteString(expr.Op.String())
908 p.arithmExprRecurse(expr.Y, compact, false)
909 } else {
910 p.arithmExprRecurse(expr.X, compact, spacePlusMinus)
911 if expr.Op != Comma {
912 p.space()
913 }
914 p.w.WriteString(expr.Op.String())
915 p.space()
916 p.arithmExprRecurse(expr.Y, compact, false)
917 }
918 case *UnaryArithm:
919 if expr.Post {
920 p.arithmExprRecurse(expr.X, compact, spacePlusMinus)
921 p.w.WriteString(expr.Op.String())
922 } else {
923 if spacePlusMinus {
924 switch expr.Op {
925 case Plus, Minus:
926 p.space()
927 }
928 }
929 p.w.WriteString(expr.Op.String())
930 if expr.Op == Not && !compact {
931 // "!" followed by a word triggers history expansion
932 // in interactive shells; a space prevents that.
933 p.space()
934 }
935 p.arithmExprRecurse(expr.X, compact, false)
936 }
937 case *ParenArithm:
938 p.w.WriteByte('(')
939 p.arithmExprRecurse(expr.X, false, false)
940 p.w.WriteByte(')')
941 case *FlagsArithm:
942 p.w.WriteByte('(')
943 p.w.WriteString(expr.Flags.Value)
944 p.w.WriteByte(')')
945 if expr.X != nil {
946 p.arithmExprRecurse(expr.X, compact, false)
947 }
948 }
949 }
950
951 func (p *Printer) testExpr(expr TestExpr) {
952 // Multi-line test expressions don't need to escape newlines.
953 if expr.Pos().Line() > p.line {
954 p.newlines(expr.Pos())
955 p.spacePad(expr.Pos())
956 } else if p.wantSpace == spaceRequired {
957 p.space()
958 }
959 p.testExprSameLine(expr)
960 }
961
962 func (p *Printer) testExprSameLine(expr TestExpr) {
963 p.advanceLine(expr.Pos().Line())
964 switch expr := expr.(type) {
965 case *Word:
966 p.word(expr)
967 case *BinaryTest:
968 p.testExprSameLine(expr.X)
969 p.space()
970 p.w.WriteString(expr.Op.String())
971 switch expr.Op {
972 case AndTest, OrTest:
973 p.wantSpace = spaceRequired
974 p.testExpr(expr.Y)
975 default:
976 p.space()
977 p.testExprSameLine(expr.Y)
978 }
979 case *UnaryTest:
980 p.w.WriteString(expr.Op.String())
981 p.space()
982 p.testExprSameLine(expr.X)
983 case *ParenTest:
984 p.w.WriteByte('(')
985 if startsWithLparen(expr.X) {
986 p.wantSpace = spaceRequired
987 } else {
988 p.wantSpace = spaceNotRequired
989 }
990 p.testExpr(expr.X)
991 p.w.WriteByte(')')
992 }
993 }
994
995 func (p *Printer) word(w *Word) {
996 p.wordParts(w.Parts, false)
997 p.wantSpace = spaceRequired
998 }
999
1000 func (p *Printer) unquotedWord(w *Word) {
1001 for _, wp := range w.Parts {
1002 switch wp := wp.(type) {
1003 case *SglQuoted:
1004 p.writeLit(wp.Value)
1005 case *DblQuoted:
1006 p.wordParts(wp.Parts, true)
1007 case *Lit:
1008 for i := 0; i < len(wp.Value); i++ {
1009 if b := wp.Value[i]; b == '\\' {
1010 if i++; i < len(wp.Value) {
1011 p.w.WriteByte(wp.Value[i])
1012 }
1013 } else {
1014 p.w.WriteByte(b)
1015 }
1016 }
1017 }
1018 }
1019 }
1020
1021 func (p *Printer) wordJoin(ws []*Word) {
1022 anyNewline := false
1023 for _, w := range ws {
1024 if pos := w.Pos(); pos.Line() > p.line && !p.singleLine {
1025 if !anyNewline {
1026 p.incLevel()
1027 anyNewline = true
1028 }
1029 p.bslashNewl()
1030 }
1031 p.spacePad(w.Pos())
1032 p.word(w)
1033 }
1034 if anyNewline {
1035 p.decLevel()
1036 }
1037 }
1038
1039 func (p *Printer) casePatternJoin(pats []*Word) {
1040 anyNewline := false
1041 for i, w := range pats {
1042 // Only valid situation for a literal 'esac' here is with a preceding left paran.
1043 if i == 0 && w.Lit() == "esac" {
1044 p.w.WriteString("(")
1045 }
1046 if i > 0 {
1047 p.spacedToken("|", Pos{})
1048 }
1049 if p.wantsNewline(w.Pos(), true) {
1050 if !anyNewline {
1051 p.incLevel()
1052 anyNewline = true
1053 }
1054 p.bslashNewl()
1055 } else {
1056 p.spacePad(w.Pos())
1057 }
1058 p.word(w)
1059 }
1060 if anyNewline {
1061 p.decLevel()
1062 }
1063 }
1064
1065 func (p *Printer) elemJoin(elems []*ArrayElem, last []Comment) {
1066 p.incLevel()
1067 for _, el := range elems {
1068 var left []Comment
1069 for _, c := range el.Comments {
1070 if c.Pos().After(el.Pos()) {
1071 left = append(left, c)
1072 break
1073 }
1074 p.comments(c)
1075 }
1076 // Multi-line array expressions don't need to escape newlines.
1077 if el.Pos().Line() > p.line {
1078 p.newlines(el.Pos())
1079 p.spacePad(el.Pos())
1080 } else if p.wantSpace == spaceRequired {
1081 p.space()
1082 }
1083 if p.wroteIndex(el.Index) {
1084 p.w.WriteByte('=')
1085 }
1086 if el.Value != nil {
1087 p.word(el.Value)
1088 }
1089 p.comments(left...)
1090 }
1091 if len(last) > 0 {
1092 p.comments(last...)
1093 p.flushComments()
1094 }
1095 p.decLevel()
1096 }
1097
1098 func (p *Printer) stmt(s *Stmt) {
1099 p.wroteSemi = false
1100 if s.Negated {
1101 p.spacedString("!", s.Pos())
1102 }
1103 var startRedirs int
1104 if s.Cmd != nil {
1105 startRedirs = p.command(s.Cmd, s.Redirs)
1106 }
1107 p.incLevel()
1108 for _, r := range s.Redirs[startRedirs:] {
1109 if p.wantsNewline(r.OpPos, true) {
1110 p.bslashNewl()
1111 }
1112 if p.wantSpace == spaceRequired {
1113 p.spacePad(r.Pos())
1114 }
1115 if r.N != nil {
1116 p.writeLit(r.N.Value)
1117 }
1118 p.w.WriteString(r.Op.String())
1119 if p.spaceRedirects && (r.Op != DplIn && r.Op != DplOut) {
1120 p.space()
1121 } else {
1122 p.wantSpace = spaceRequired
1123 }
1124 p.word(r.Word)
1125 if r.Op == Hdoc || r.Op == DashHdoc {
1126 p.pendingHdocs = append(p.pendingHdocs, r)
1127 }
1128 }
1129 sep := s.Semicolon.IsValid() && s.Semicolon.Line() > p.line && !p.singleLine
1130 if sep || s.Background || s.Coprocess || s.Disown {
1131 if sep {
1132 p.bslashNewl()
1133 } else if !p.minify {
1134 p.space()
1135 }
1136 if s.Background {
1137 p.w.WriteString("&")
1138 } else if s.Coprocess {
1139 p.w.WriteString("|&")
1140 } else if s.Disown {
1141 p.w.WriteString("&|")
1142 } else {
1143 p.w.WriteString(";")
1144 }
1145 p.wroteSemi = true
1146 p.wantSpace = spaceRequired
1147 }
1148 p.decLevel()
1149 }
1150
1151 func (p *Printer) printRedirsUntil(redirs []*Redirect, startRedirs int, pos Pos) int {
1152 for _, r := range redirs[startRedirs:] {
1153 if r.Pos().After(pos) || r.Op == Hdoc || r.Op == DashHdoc {
1154 break
1155 }
1156 if p.wantSpace == spaceRequired {
1157 p.spacePad(r.Pos())
1158 }
1159 if r.N != nil {
1160 p.writeLit(r.N.Value)
1161 }
1162 p.w.WriteString(r.Op.String())
1163 if p.spaceRedirects && (r.Op != DplIn && r.Op != DplOut) {
1164 p.space()
1165 } else {
1166 p.wantSpace = spaceRequired
1167 }
1168 p.word(r.Word)
1169 startRedirs++
1170 }
1171 return startRedirs
1172 }
1173
1174 func (p *Printer) command(cmd Command, redirs []*Redirect) (startRedirs int) {
1175 p.advanceLine(cmd.Pos().Line())
1176 p.spacePad(cmd.Pos())
1177 switch cmd := cmd.(type) {
1178 case *CallExpr:
1179 p.assigns(cmd.Assigns)
1180 if len(cmd.Args) > 0 {
1181 startRedirs = p.printRedirsUntil(redirs, startRedirs, cmd.Args[0].Pos())
1182 }
1183 if len(cmd.Args) <= 1 {
1184 p.wordJoin(cmd.Args)
1185 return startRedirs
1186 }
1187 p.wordJoin(cmd.Args[:1])
1188 startRedirs = p.printRedirsUntil(redirs, startRedirs, cmd.Args[1].Pos())
1189 p.wordJoin(cmd.Args[1:])
1190 case *Block:
1191 p.w.WriteByte('{')
1192 // avoid ; in an empty block
1193 p.wroteSemi = true
1194 p.wantSpace = spaceRequired
1195 // Forbid "foo()\n{ bar; }"
1196 p.wantNewline = p.wantNewline || p.funcNextLine
1197 p.nestedStmts(cmd.Stmts, cmd.Last, cmd.Rbrace)
1198 p.semiRsrv("}", cmd.Rbrace)
1199 case *IfClause:
1200 p.ifClause(cmd, false)
1201 case *Subshell:
1202 p.w.WriteByte('(')
1203 stmts := cmd.Stmts
1204 if len(stmts) > 0 && startsWithLparen(stmts[0]) {
1205 p.wantSpace = spaceRequired
1206 // Add a space between nested parentheses if we're printing them in a single line,
1207 // to avoid the ambiguity between `((` and `( (`.
1208 if (cmd.Lparen.Line() != stmts[0].Pos().Line() || len(stmts) > 1) && !p.singleLine {
1209 p.wantSpace = spaceNotRequired
1210
1211 if p.minify {
1212 p.mustNewline = true
1213 }
1214 }
1215 } else if len(stmts) == 0 {
1216 // Zsh allows empty subshells, but prevent `()`
1217 // from looking like `() { anon-func; }`.
1218 p.wantSpace = spaceRequired
1219 } else {
1220 p.wantSpace = spaceNotRequired
1221 }
1222
1223 p.spacePad(stmtsPos(cmd.Stmts, cmd.Last))
1224 p.nestedStmts(cmd.Stmts, cmd.Last, cmd.Rparen)
1225 p.closingParen(cmd.Stmts, cmd.Last, cmd.Lparen, cmd.Rparen)
1226 case *WhileClause:
1227 if cmd.Until {
1228 p.spacedString("until", cmd.Pos())
1229 } else {
1230 p.spacedString("while", cmd.Pos())
1231 }
1232 p.nestedStmts(cmd.Cond, cmd.CondLast, Pos{})
1233 p.semiOrNewl("do", cmd.DoPos)
1234 p.nestedStmts(cmd.Do, cmd.DoLast, cmd.DonePos)
1235 p.semiRsrv("done", cmd.DonePos)
1236 case *ForClause:
1237 if cmd.Select {
1238 p.w.WriteString("select ")
1239 } else {
1240 p.w.WriteString("for ")
1241 }
1242 p.loop(cmd.Loop)
1243 p.semiOrNewl("do", cmd.DoPos)
1244 p.nestedStmts(cmd.Do, cmd.DoLast, cmd.DonePos)
1245 p.semiRsrv("done", cmd.DonePos)
1246 case *BinaryCmd:
1247 p.stmt(cmd.X)
1248 if p.minify || p.singleLine || cmd.Y.Pos().Line() <= p.line {
1249 // leave p.nestedBinary untouched
1250 p.spacedToken(cmd.Op.String(), cmd.OpPos)
1251 p.advanceLine(cmd.Y.Pos().Line())
1252 p.stmt(cmd.Y)
1253 break
1254 }
1255 indent := !p.nestedBinary
1256 if indent {
1257 p.incLevel()
1258 }
1259 if p.binNextLine {
1260 if len(p.pendingHdocs) == 0 {
1261 p.bslashNewl()
1262 }
1263 p.spacedToken(cmd.Op.String(), cmd.OpPos)
1264 if len(cmd.Y.Comments) > 0 {
1265 p.wantSpace = spaceNotRequired
1266 p.newline(cmd.Y.Pos())
1267 p.indent()
1268 p.comments(cmd.Y.Comments...)
1269 p.newline(Pos{})
1270 p.indent()
1271 }
1272 } else {
1273 p.spacedToken(cmd.Op.String(), cmd.OpPos)
1274 p.advanceLine(cmd.OpPos.Line())
1275 p.comments(cmd.Y.Comments...)
1276 p.newline(Pos{})
1277 p.indent()
1278 }
1279 p.advanceLine(cmd.Y.Pos().Line())
1280 _, p.nestedBinary = cmd.Y.Cmd.(*BinaryCmd)
1281 p.stmt(cmd.Y)
1282 if indent {
1283 p.decLevel()
1284 }
1285 p.nestedBinary = false
1286 case *FuncDecl:
1287 if cmd.RsrvWord {
1288 p.spacedString("function", Pos{})
1289 }
1290 if cmd.Name != nil {
1291 p.spacedString(cmd.Name.Value, Pos{})
1292 } else {
1293 for _, name := range cmd.Names {
1294 p.spacedString(name.Value, Pos{})
1295 }
1296 }
1297 if !cmd.RsrvWord || cmd.Parens {
1298 p.w.WriteString("()")
1299 p.wantSpace = spaceNotRequired
1300 }
1301 if p.funcNextLine {
1302 p.newline(Pos{})
1303 p.indent()
1304 } else if !cmd.Parens || !p.minify {
1305 p.space()
1306 }
1307 p.advanceLine(cmd.Body.Pos().Line())
1308 p.comments(cmd.Body.Comments...)
1309 p.stmt(cmd.Body)
1310 case *CaseClause:
1311 p.w.WriteString("case ")
1312 p.word(cmd.Word)
1313 p.w.WriteString(" in")
1314 p.advanceLine(cmd.In.Line())
1315 p.wantSpace = spaceRequired
1316 if p.swtCaseIndent {
1317 p.incLevel()
1318 }
1319 if len(cmd.Items) == 0 {
1320 // Apparently "case x in; esac" is invalid shell.
1321 p.mustNewline = true
1322 }
1323 for i, ci := range cmd.Items {
1324 var last []Comment
1325 for i, c := range ci.Comments {
1326 if c.Pos().After(ci.Pos()) {
1327 last = ci.Comments[i:]
1328 break
1329 }
1330 p.comments(c)
1331 }
1332 p.newlines(ci.Pos())
1333 p.spacePad(ci.Pos())
1334 p.casePatternJoin(ci.Patterns)
1335 p.w.WriteByte(')')
1336 if !p.minify {
1337 p.wantSpace = spaceRequired
1338 } else {
1339 p.wantSpace = spaceNotRequired
1340 }
1341
1342 p.nestedStmts(ci.Stmts, ci.Last, ci.OpPos)
1343 p.level++
1344 if !p.minify || i != len(cmd.Items)-1 {
1345 if p.wantsNewline(ci.OpPos, false) {
1346 p.newlines(ci.OpPos)
1347 p.wantNewline = true
1348 }
1349 p.spacedToken(ci.Op.String(), ci.OpPos)
1350 p.advanceLine(ci.OpPos.Line())
1351 // avoid ; directly after tokens like ;;
1352 p.wroteSemi = true
1353 }
1354 p.comments(last...)
1355 p.flushComments()
1356 p.level--
1357 }
1358 p.comments(cmd.Last...)
1359 if p.swtCaseIndent {
1360 p.flushComments()
1361 p.decLevel()
1362 }
1363 p.semiRsrv("esac", cmd.Esac)
1364 case *ArithmCmd:
1365 p.w.WriteString("((")
1366 if cmd.Unsigned {
1367 p.w.WriteString("# ")
1368 }
1369 p.arithmExpr(cmd.X, false, false)
1370 p.w.WriteString("))")
1371 case *TestClause:
1372 p.w.WriteString("[[ ")
1373 p.incLevel()
1374 p.testExpr(cmd.X)
1375 p.decLevel()
1376 p.spacedString("]]", cmd.Right)
1377 case *DeclClause:
1378 p.spacedString(cmd.Variant.Value, cmd.Pos())
1379 p.assigns(cmd.Args)
1380 case *TimeClause:
1381 p.spacedString("time", cmd.Pos())
1382 if cmd.PosixFormat {
1383 p.spacedString("-p", cmd.Pos())
1384 }
1385 if cmd.Stmt != nil {
1386 p.stmt(cmd.Stmt)
1387 }
1388 case *CoprocClause:
1389 p.spacedString("coproc", cmd.Pos())
1390 if cmd.Name != nil {
1391 p.space()
1392 p.word(cmd.Name)
1393 }
1394 p.space()
1395 p.stmt(cmd.Stmt)
1396 case *LetClause:
1397 p.spacedString("let", cmd.Pos())
1398 for _, n := range cmd.Exprs {
1399 p.space()
1400 p.arithmExpr(n, true, false)
1401 }
1402 case *TestDecl:
1403 p.spacedString("@test", cmd.Pos())
1404 p.space()
1405 p.word(cmd.Description)
1406 p.space()
1407 p.stmt(cmd.Body)
1408 default:
1409 panic(fmt.Sprintf("syntax.Printer: unexpected node type %T", cmd))
1410 }
1411 return startRedirs
1412 }
1413
1414 func (p *Printer) ifClause(ic *IfClause, elif bool) {
1415 if !elif {
1416 p.spacedString("if", ic.Pos())
1417 }
1418 p.nestedStmts(ic.Cond, ic.CondLast, Pos{})
1419 p.semiOrNewl("then", ic.ThenPos)
1420 thenEnd := ic.FiPos
1421 el := ic.Else
1422 if el != nil {
1423 thenEnd = el.Position
1424 }
1425 p.nestedStmts(ic.Then, ic.ThenLast, thenEnd)
1426
1427 if el != nil && el.ThenPos.IsValid() {
1428 p.comments(ic.Last...)
1429 p.semiRsrv("elif", el.Position)
1430 p.ifClause(el, true)
1431 return
1432 }
1433 if el == nil {
1434 p.comments(ic.Last...)
1435 } else {
1436 var left []Comment
1437 for _, c := range ic.Last {
1438 if c.Pos().After(el.Position) {
1439 left = append(left, c)
1440 break
1441 }
1442 p.comments(c)
1443 }
1444 p.semiRsrv("else", el.Position)
1445 p.comments(left...)
1446 p.nestedStmts(el.Then, el.ThenLast, ic.FiPos)
1447 p.comments(el.Last...)
1448 }
1449 p.semiRsrv("fi", ic.FiPos)
1450 }
1451
1452 func (p *Printer) stmtList(stmts []*Stmt, last []Comment) {
1453 sep := p.wantNewline || (len(stmts) > 0 && stmts[0].Pos().Line() > p.line)
1454 for i, s := range stmts {
1455 if i > 0 && p.singleLine && p.wantNewline && !p.wroteSemi {
1456 // In singleLine mode, ensure we use semicolons between
1457 // statements.
1458 p.w.WriteByte(';')
1459 p.wantSpace = spaceRequired
1460 }
1461 pos := s.Pos()
1462 var midComs, endComs []Comment
1463 for _, c := range s.Comments {
1464 // Comments after the end of this command. Note that
1465 // this includes "<<EOF # comment".
1466 if s.Cmd != nil && c.End().After(s.Cmd.End()) {
1467 endComs = append(endComs, c)
1468 break
1469 }
1470 // Comments between the beginning of the statement and
1471 // the end of the command.
1472 if c.Pos().After(pos) {
1473 midComs = append(midComs, c)
1474 continue
1475 }
1476 // The rest of the comments are before the entire
1477 // statement.
1478 p.comments(c)
1479 }
1480 if p.mustNewline || !p.minify || p.wantSpace == spaceRequired {
1481 p.newlines(pos)
1482 }
1483 p.advanceLine(pos.Line())
1484 p.comments(midComs...)
1485 p.stmt(s)
1486 p.comments(endComs...)
1487 p.wantNewline = true
1488 }
1489 if len(stmts) == 1 && !sep {
1490 p.wantNewline = false
1491 }
1492 p.comments(last...)
1493 }
1494
1495 func (p *Printer) nestedStmts(stmts []*Stmt, last []Comment, closing Pos) {
1496 p.incLevel()
1497 switch {
1498 case len(stmts) > 1:
1499 // Force a newline if we find:
1500 // { stmt; stmt; }
1501 p.wantNewline = true
1502 case closing.Line() > p.line && len(stmts) > 0 &&
1503 stmtsEnd(stmts, last).Line() < closing.Line():
1504 // Force a newline if we find:
1505 // { stmt
1506 // }
1507 p.wantNewline = true
1508 case len(p.pendingComments) > 0 && len(stmts) > 0:
1509 // Force a newline if we find:
1510 // for i in a b # stmt
1511 // do foo; done
1512 p.wantNewline = true
1513 }
1514 p.stmtList(stmts, last)
1515 if closing.IsValid() {
1516 p.flushComments()
1517 }
1518 p.decLevel()
1519 }
1520
1521 func (p *Printer) assigns(assigns []*Assign) {
1522 p.incLevel()
1523 for _, a := range assigns {
1524 if p.wantsNewline(a.Pos(), true) {
1525 p.bslashNewl()
1526 } else {
1527 p.spacePad(a.Pos())
1528 }
1529 if a.Name != nil {
1530 p.writeLit(a.Name.Value)
1531 p.wroteIndex(a.Index)
1532 if a.Append {
1533 p.w.WriteByte('+')
1534 }
1535 if !a.Naked {
1536 p.w.WriteByte('=')
1537 }
1538 }
1539 if a.Value != nil {
1540 // Ensure we don't use an escaped newline after '=',
1541 // because that can result in indentation, thus
1542 // splitting "foo=bar" into "foo= bar".
1543 p.advanceLine(a.Value.Pos().Line())
1544 p.word(a.Value)
1545 } else if a.Array != nil {
1546 p.wantSpace = spaceNotRequired
1547 p.w.WriteByte('(')
1548 p.elemJoin(a.Array.Elems, a.Array.Last)
1549 p.rightParen(a.Array.Rparen)
1550 }
1551 p.wantSpace = spaceRequired
1552 }
1553 p.decLevel()
1554 }
1555
1556 type wantSpaceState uint8
1557
1558 const (
1559 spaceNotRequired wantSpaceState = iota
1560 spaceRequired // we should generally print a space or a newline next
1561 spaceWritten // we have just written a space or newline
1562 )
1563
1564 // extraIndenter ensures that all lines in a '<<-' heredoc body have at least
1565 // baseIndent leading tabs. Those that had more tab indentation than the first
1566 // heredoc line will keep that relative indentation.
1567 type extraIndenter struct {
1568 bufWriter
1569 baseIndent int
1570
1571 firstIndent int
1572 firstChange int
1573 curLine []byte
1574 }
1575
1576 func (e *extraIndenter) WriteByte(b byte) error {
1577 e.curLine = append(e.curLine, b)
1578 if b != '\n' {
1579 return nil
1580 }
1581 trimmed := bytes.TrimLeft(e.curLine, "\t")
1582 if len(trimmed) == 1 {
1583 // no tabs if this is an empty line, i.e. "\n"
1584 e.bufWriter.Write(trimmed)
1585 e.curLine = e.curLine[:0]
1586 return nil
1587 }
1588
1589 lineIndent := len(e.curLine) - len(trimmed)
1590 if e.firstIndent < 0 {
1591 // This is the first heredoc line we add extra indentation to.
1592 // Keep track of how much we indented.
1593 e.firstIndent = lineIndent
1594 e.firstChange = e.baseIndent - lineIndent
1595 lineIndent = e.baseIndent
1596
1597 } else if lineIndent < e.firstIndent {
1598 // This line did not have enough indentation; simply indent it
1599 // like the first line.
1600 lineIndent = e.firstIndent
1601 } else {
1602 // This line had plenty of indentation. Add the extra
1603 // indentation that the first line had, for consistency.
1604 lineIndent += e.firstChange
1605 }
1606 e.bufWriter.WriteByte(tabwriter.Escape)
1607 for range lineIndent {
1608 e.bufWriter.WriteByte('\t')
1609 }
1610 e.bufWriter.WriteByte(tabwriter.Escape)
1611 e.bufWriter.Write(trimmed)
1612 e.curLine = e.curLine[:0]
1613 return nil
1614 }
1615
1616 func (e *extraIndenter) WriteString(s string) (int, error) {
1617 for i := range len(s) {
1618 e.WriteByte(s[i])
1619 }
1620 return len(s), nil
1621 }
1622
1623 func startsWithLparen(node Node) bool {
1624 switch node := node.(type) {
1625 case *Stmt:
1626 return startsWithLparen(node.Cmd)
1627 case *BinaryCmd:
1628 return startsWithLparen(node.X)
1629 case *Subshell:
1630 return true // keep ( (
1631 case *ArithmCmd:
1632 return true // keep ( ((
1633 }
1634 return false
1635 }
1636
1637 func endsWithRparen(node Node) bool {
1638 switch node := node.(type) {
1639 case *Stmt:
1640 if node.Background || node.Coprocess || node.Disown || len(node.Redirs) > 0 {
1641 return false
1642 }
1643 return endsWithRparen(node.Cmd)
1644 case *BinaryCmd:
1645 return endsWithRparen(node.Y)
1646 case *Subshell:
1647 return true // keep ) )
1648 case *ArithmCmd:
1649 return true // keep )) )
1650 }
1651 return false
1652 }