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