forked from mvdan/sh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprinter.go
1538 lines (1439 loc) · 35.8 KB
/
printer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2016, Daniel Martí <[email protected]>
// See LICENSE for licensing information
package syntax
import (
"bufio"
"bytes"
"fmt"
"io"
"strings"
"text/tabwriter"
"unicode"
"mvdan.cc/sh/v3/fileutil"
)
// PrinterOption is a function which can be passed to NewPrinter
// to alter its behavior. To apply option to existing Printer
// call it directly, for example KeepPadding(true)(printer).
type PrinterOption func(*Printer)
// Indent sets the number of spaces used for indentation. If set to 0,
// tabs will be used instead.
func Indent(spaces uint) PrinterOption {
return func(p *Printer) { p.indentSpaces = spaces }
}
// BinaryNextLine will make binary operators appear on the next line
// when a binary command, such as a pipe, spans multiple lines. A
// backslash will be used.
func BinaryNextLine(enabled bool) PrinterOption {
return func(p *Printer) { p.binNextLine = enabled }
}
// SwitchCaseIndent will make switch cases be indented. As such, switch
// case bodies will be two levels deeper than the switch itself.
func SwitchCaseIndent(enabled bool) PrinterOption {
return func(p *Printer) { p.swtCaseIndent = enabled }
}
// TODO(v4): consider turning this into a "space all operators" option, to also
// allow foo=( bar baz ), (( x + y )), and so on.
// SpaceRedirects will put a space after most redirection operators. The
// exceptions are '>&', '<&', '>(', and '<('.
func SpaceRedirects(enabled bool) PrinterOption {
return func(p *Printer) { p.spaceRedirects = enabled }
}
// KeepPadding will keep most nodes and tokens in the same column that
// they were in the original source. This allows the user to decide how
// to align and pad their code with spaces.
//
// Note that this feature is best-effort and will only keep the
// alignment stable, so it may need some human help the first time it is
// run.
func KeepPadding(enabled bool) PrinterOption {
return func(p *Printer) {
if enabled && !p.keepPadding {
// Enable the flag, and set up the writer wrapper.
p.keepPadding = true
p.cols.Writer = p.bufWriter.(*bufio.Writer)
p.bufWriter = &p.cols
} else if !enabled && p.keepPadding {
// Ensure we reset the state to that of NewPrinter.
p.keepPadding = false
p.bufWriter = p.cols.Writer
p.cols = colCounter{}
}
}
}
// Minify will print programs in a way to save the most bytes possible.
// For example, indentation and comments are skipped, and extra
// whitespace is avoided when possible.
func Minify(enabled bool) PrinterOption {
return func(p *Printer) { p.minify = enabled }
}
// SingleLine will attempt to print programs in one line. For example, lists of
// commands or nested blocks do not use newlines in this mode. Note that some
// newlines must still appear, such as those following comments or around
// here-documents.
//
// Print's trailing newline when given a *File is not affected by this option.
func SingleLine(enabled bool) PrinterOption {
return func(p *Printer) { p.singleLine = enabled }
}
// FunctionNextLine will place a function's opening braces on the next line.
func FunctionNextLine(enabled bool) PrinterOption {
return func(p *Printer) { p.funcNextLine = enabled }
}
// NewPrinter allocates a new Printer and applies any number of options.
func NewPrinter(opts ...PrinterOption) *Printer {
p := &Printer{
bufWriter: bufio.NewWriter(nil),
tabWriter: new(tabwriter.Writer),
}
for _, opt := range opts {
opt(p)
}
return p
}
// Print "pretty-prints" the given syntax tree node to the given writer. Writes
// to w are buffered.
//
// The node types supported at the moment are *File, *Stmt, *Word, *Assign, any
// Command node, and any WordPart node. A trailing newline will only be printed
// when a *File is used.
func (p *Printer) Print(w io.Writer, node Node) error {
p.reset()
if p.minify && p.singleLine {
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")
}
// TODO: consider adding a raw mode to skip the tab writer, much like in
// go/printer.
twmode := tabwriter.DiscardEmptyColumns | tabwriter.StripEscape
tabwidth := 8
if p.indentSpaces == 0 {
// indenting with tabs
twmode |= tabwriter.TabIndent
} else {
// indenting with spaces
tabwidth = int(p.indentSpaces)
}
p.tabWriter.Init(w, 0, tabwidth, 1, ' ', twmode)
w = p.tabWriter
p.bufWriter.Reset(w)
switch x := node.(type) {
case *File:
p.stmtList(x.Stmts, x.Last)
p.newline(Pos{})
case *Stmt:
p.stmtList([]*Stmt{x}, nil)
case Command:
p.command(x, nil)
case *Word:
p.line = x.Pos().Line()
p.word(x)
case WordPart:
p.line = x.Pos().Line()
p.wordPart(x, nil)
case *Assign:
p.line = x.Pos().Line()
p.assigns([]*Assign{x})
default:
return fmt.Errorf("unsupported node type: %T", x)
}
p.flushHeredocs()
p.flushComments()
// flush the writers
if err := p.bufWriter.Flush(); err != nil {
return err
}
if tw, _ := w.(*tabwriter.Writer); tw != nil {
if err := tw.Flush(); err != nil {
return err
}
}
return nil
}
type bufWriter interface {
Write([]byte) (int, error)
WriteString(string) (int, error)
WriteByte(byte) error
Reset(io.Writer)
Flush() error
}
type colCounter struct {
*bufio.Writer
column int
lineStart bool
}
func (c *colCounter) addByte(b byte) {
switch b {
case '\n':
c.column = 0
c.lineStart = true
case '\t', ' ', tabwriter.Escape:
default:
c.lineStart = false
}
c.column++
}
func (c *colCounter) WriteByte(b byte) error {
c.addByte(b)
return c.Writer.WriteByte(b)
}
func (c *colCounter) WriteString(s string) (int, error) {
for _, b := range []byte(s) {
c.addByte(b)
}
return c.Writer.WriteString(s)
}
func (c *colCounter) Reset(w io.Writer) {
c.column = 1
c.lineStart = true
c.Writer.Reset(w)
}
// Printer holds the internal state of the printing mechanism of a
// program.
type Printer struct {
bufWriter // TODO: embedding this makes the methods part of the API, which we did not intend
tabWriter *tabwriter.Writer
cols colCounter
indentSpaces uint
binNextLine bool
swtCaseIndent bool
spaceRedirects bool
keepPadding bool
minify bool
singleLine bool
funcNextLine bool
wantSpace wantSpaceState // whether space is required or has been written
wantNewline bool // newline is wanted for pretty-printing; ignored by singleLine; ignored by singleLine
mustNewline bool // newline is required to keep shell syntax valid
wroteSemi bool // wrote ';' for the current statement
// pendingComments are any comments in the current line or statement
// that we have yet to print. This is useful because that way, we can
// ensure that all comments are written immediately before a newline.
// Otherwise, in some edge cases we might wrongly place words after a
// comment in the same line, breaking programs.
pendingComments []Comment
// firstLine means we are still writing the first line
firstLine bool
// line is the current line number
line uint
// lastLevel is the last level of indentation that was used.
lastLevel uint
// level is the current level of indentation.
level uint
// levelIncs records which indentation level increments actually
// took place, to revert them once their section ends.
levelIncs []bool
nestedBinary bool
// pendingHdocs is the list of pending heredocs to write.
pendingHdocs []*Redirect
// used when printing <<- heredocs with tab indentation
tabsPrinter *Printer
}
func (p *Printer) reset() {
p.wantSpace = spaceWritten
p.wantNewline, p.mustNewline = false, false
p.pendingComments = p.pendingComments[:0]
// minification uses its own newline logic
p.firstLine = !p.minify
p.line = 0
p.lastLevel, p.level = 0, 0
p.levelIncs = p.levelIncs[:0]
p.nestedBinary = false
p.pendingHdocs = p.pendingHdocs[:0]
}
func (p *Printer) spaces(n uint) {
for i := uint(0); i < n; i++ {
p.WriteByte(' ')
}
}
func (p *Printer) space() {
p.WriteByte(' ')
p.wantSpace = spaceWritten
}
func (p *Printer) spacePad(pos Pos) {
if p.cols.lineStart && p.indentSpaces == 0 {
// Never add padding at the start of a line unless we are indenting
// with spaces, since this may result in mixing of spaces and tabs.
return
}
if p.wantSpace == spaceRequired {
p.WriteByte(' ')
p.wantSpace = spaceWritten
}
for p.cols.column > 0 && p.cols.column < int(pos.Col()) {
p.WriteByte(' ')
}
}
// wantsNewline reports whether we want to print at least one newline before
// printing a node at a given position. A zero position can be given to simply
// tell if we want a newline following what's just been printed.
func (p *Printer) wantsNewline(pos Pos, escapingNewline bool) bool {
if p.mustNewline {
// We must have a newline here.
return true
}
if p.singleLine && len(p.pendingComments) == 0 {
// The newline is optional, and singleLine skips it.
// Don't skip if there are any pending comments,
// as that might move them further down to the wrong place.
return false
}
if escapingNewline && p.minify {
return false
}
// The newline is optional, and we want it via either wantNewline or via
// the position's line.
return p.wantNewline || pos.Line() > p.line
}
func (p *Printer) bslashNewl() {
if p.wantSpace == spaceRequired {
p.space()
}
p.WriteString("\\\n")
p.line++
p.indent()
}
func (p *Printer) spacedString(s string, pos Pos) {
p.spacePad(pos)
p.WriteString(s)
p.wantSpace = spaceRequired
}
func (p *Printer) spacedToken(s string, pos Pos) {
if p.minify {
p.WriteString(s)
p.wantSpace = spaceNotRequired
return
}
p.spacePad(pos)
p.WriteString(s)
p.wantSpace = spaceRequired
}
func (p *Printer) semiOrNewl(s string, pos Pos) {
if p.wantsNewline(Pos{}, false) {
p.newline(pos)
p.indent()
} else {
if !p.wroteSemi {
p.WriteByte(';')
}
if !p.minify {
p.space()
}
p.advanceLine(pos.Line())
}
p.WriteString(s)
p.wantSpace = spaceRequired
}
func (p *Printer) writeLit(s string) {
// If p.tabWriter is nil, this is the nested printer being used to print
// <<- heredoc bodies, so the parent printer will add the escape bytes
// later.
if p.tabWriter != nil && strings.Contains(s, "\t") {
p.WriteByte(tabwriter.Escape)
defer p.WriteByte(tabwriter.Escape)
}
p.WriteString(s)
}
func (p *Printer) incLevel() {
inc := false
if p.level <= p.lastLevel || len(p.levelIncs) == 0 {
p.level++
inc = true
} else if last := &p.levelIncs[len(p.levelIncs)-1]; *last {
*last = false
inc = true
}
p.levelIncs = append(p.levelIncs, inc)
}
func (p *Printer) decLevel() {
if p.levelIncs[len(p.levelIncs)-1] {
p.level--
}
p.levelIncs = p.levelIncs[:len(p.levelIncs)-1]
}
func (p *Printer) indent() {
if p.minify {
return
}
p.lastLevel = p.level
switch {
case p.level == 0:
case p.indentSpaces == 0:
p.WriteByte(tabwriter.Escape)
for i := uint(0); i < p.level; i++ {
p.WriteByte('\t')
}
p.WriteByte(tabwriter.Escape)
default:
p.spaces(p.indentSpaces * p.level)
}
}
// TODO(mvdan): add an indent call at the end of newline?
// newline prints one newline and advances p.line to pos.Line().
func (p *Printer) newline(pos Pos) {
p.flushHeredocs()
p.flushComments()
p.WriteByte('\n')
p.wantSpace = spaceWritten
p.wantNewline, p.mustNewline = false, false
p.advanceLine(pos.Line())
}
func (p *Printer) advanceLine(line uint) {
if p.line < line {
p.line = line
}
}
func (p *Printer) flushHeredocs() {
if len(p.pendingHdocs) == 0 {
return
}
hdocs := p.pendingHdocs
p.pendingHdocs = p.pendingHdocs[:0]
coms := p.pendingComments
p.pendingComments = nil
if len(coms) > 0 {
c := coms[0]
if c.Pos().Line() == p.line {
p.pendingComments = append(p.pendingComments, c)
p.flushComments()
coms = coms[1:]
}
}
// Reuse the last indentation level, as
// indentation levels are usually changed before
// newlines are printed along with their
// subsequent indentation characters.
newLevel := p.level
p.level = p.lastLevel
for _, r := range hdocs {
p.line++
p.WriteByte('\n')
p.wantSpace = spaceWritten
p.wantNewline, p.wantNewline = false, false
if r.Op == DashHdoc && p.indentSpaces == 0 && !p.minify {
if r.Hdoc != nil {
extra := extraIndenter{
bufWriter: p.bufWriter,
baseIndent: int(p.level + 1),
firstIndent: -1,
}
p.tabsPrinter = &Printer{
bufWriter: &extra,
// The options need to persist.
indentSpaces: p.indentSpaces,
binNextLine: p.binNextLine,
swtCaseIndent: p.swtCaseIndent,
spaceRedirects: p.spaceRedirects,
keepPadding: p.keepPadding,
minify: p.minify,
funcNextLine: p.funcNextLine,
line: r.Hdoc.Pos().Line(),
}
p.tabsPrinter.wordParts(r.Hdoc.Parts, true)
}
p.indent()
} else if r.Hdoc != nil {
p.wordParts(r.Hdoc.Parts, true)
}
p.unquotedWord(r.Word)
if r.Hdoc != nil {
// Overwrite p.line, since printing r.Word again can set
// p.line to the beginning of the heredoc again.
p.advanceLine(r.Hdoc.End().Line())
}
p.wantSpace = spaceNotRequired
}
p.level = newLevel
p.pendingComments = coms
p.mustNewline = true
}
// newline prints between zero and two newlines.
// If any newlines are printed, it advances p.line to pos.Line().
func (p *Printer) newlines(pos Pos) {
if p.firstLine && len(p.pendingComments) == 0 {
p.firstLine = false
return // no empty lines at the top
}
if !p.wantsNewline(pos, false) {
return
}
p.flushHeredocs()
p.flushComments()
p.WriteByte('\n')
p.wantSpace = spaceWritten
p.wantNewline, p.mustNewline = false, false
l := pos.Line()
if l > p.line+1 && !p.minify {
p.WriteByte('\n') // preserve single empty lines
}
p.advanceLine(l)
p.indent()
}
func (p *Printer) rightParen(pos Pos) {
if len(p.pendingHdocs) > 0 || !p.minify {
p.newlines(pos)
}
p.WriteByte(')')
p.wantSpace = spaceRequired
}
func (p *Printer) semiRsrv(s string, pos Pos) {
if p.wantsNewline(pos, false) {
p.newlines(pos)
} else {
if !p.wroteSemi {
p.WriteByte(';')
}
if !p.minify {
p.spacePad(pos)
}
}
p.WriteString(s)
p.wantSpace = spaceRequired
}
func (p *Printer) flushComments() {
for i, c := range p.pendingComments {
if i == 0 {
// Flush any pending heredocs first. Otherwise, the
// comments would become part of a heredoc body.
p.flushHeredocs()
}
p.firstLine = false
// We can't call any of the newline methods, as they call this
// function and we'd recurse forever.
cline := c.Hash.Line()
switch {
case p.mustNewline, i > 0, cline > p.line && p.line > 0:
p.WriteByte('\n')
if cline > p.line+1 {
p.WriteByte('\n')
}
p.indent()
p.wantSpace = spaceWritten
p.spacePad(c.Pos())
case p.wantSpace == spaceRequired:
if p.keepPadding {
p.spacePad(c.Pos())
} else {
p.WriteByte('\t')
}
case p.wantSpace != spaceWritten:
p.space()
}
// don't go back one line, which may happen in some edge cases
p.advanceLine(cline)
p.WriteByte('#')
p.writeLit(strings.TrimRightFunc(c.Text, unicode.IsSpace))
p.wantNewline = true
p.mustNewline = true
}
p.pendingComments = nil
}
func (p *Printer) comments(comments ...Comment) {
if p.minify {
for _, c := range comments {
if fileutil.Shebang([]byte("#"+c.Text)) != "" && c.Hash.Col() == 1 && c.Hash.Line() == 1 {
p.WriteString(strings.TrimRightFunc("#"+c.Text, unicode.IsSpace))
p.WriteString("\n")
p.line++
}
}
return
}
p.pendingComments = append(p.pendingComments, comments...)
}
func (p *Printer) wordParts(wps []WordPart, quoted bool) {
// We disallow unquoted escaped newlines between word parts below.
// However, we want to allow a leading escaped newline for cases such as:
//
// foo <<< \
// "bar baz"
if !quoted && !p.singleLine && wps[0].Pos().Line() > p.line {
p.bslashNewl()
}
for i, wp := range wps {
var next WordPart
if i+1 < len(wps) {
next = wps[i+1]
}
// Keep escaped newlines separating word parts when quoted.
// Note that those escaped newlines don't cause indentaiton.
// When not quoted, we strip them out consistently,
// because attempting to keep them would prevent indentation.
// Can't use p.wantsNewline here, since this is only about
// escaped newlines.
for quoted && !p.singleLine && wp.Pos().Line() > p.line {
p.WriteString("\\\n")
p.line++
}
p.wordPart(wp, next)
p.advanceLine(wp.End().Line())
}
}
func (p *Printer) wordPart(wp, next WordPart) {
switch x := wp.(type) {
case *Lit:
p.writeLit(x.Value)
case *SglQuoted:
if x.Dollar {
p.WriteByte('$')
}
p.WriteByte('\'')
p.writeLit(x.Value)
p.WriteByte('\'')
p.advanceLine(x.End().Line())
case *DblQuoted:
p.dblQuoted(x)
case *CmdSubst:
p.advanceLine(x.Pos().Line())
switch {
case x.TempFile:
p.WriteString("${")
p.wantSpace = spaceRequired
p.nestedStmts(x.Stmts, x.Last, x.Right)
p.wantSpace = spaceNotRequired
p.semiRsrv("}", x.Right)
case x.ReplyVar:
p.WriteString("${|")
p.nestedStmts(x.Stmts, x.Last, x.Right)
p.wantSpace = spaceNotRequired
p.semiRsrv("}", x.Right)
// Special case: `# inline comment`
case x.Backquotes && len(x.Stmts) == 0 &&
len(x.Last) == 1 && x.Right.Line() == p.line:
p.WriteString("`#")
p.WriteString(x.Last[0].Text)
p.WriteString("`")
default:
p.WriteString("$(")
if len(x.Stmts) > 0 && startsWithLparen(x.Stmts[0]) {
p.wantSpace = spaceRequired
} else {
p.wantSpace = spaceNotRequired
}
p.nestedStmts(x.Stmts, x.Last, x.Right)
p.rightParen(x.Right)
}
case *ParamExp:
litCont := ";"
if nextLit, ok := next.(*Lit); ok && nextLit.Value != "" {
litCont = nextLit.Value[:1]
}
name := x.Param.Value
switch {
case !p.minify:
case x.Excl, x.Length, x.Width:
case x.Index != nil, x.Slice != nil:
case x.Repl != nil, x.Exp != nil:
case len(name) > 1 && !ValidName(name): // ${10}
case ValidName(name + litCont): // ${var}cont
default:
x2 := *x
x2.Short = true
p.paramExp(&x2)
return
}
p.paramExp(x)
case *ArithmExp:
p.WriteString("$((")
if x.Unsigned {
p.WriteString("# ")
}
p.arithmExpr(x.X, false, false)
p.WriteString("))")
case *ExtGlob:
p.WriteString(x.Op.String())
p.writeLit(x.Pattern.Value)
p.WriteByte(')')
case *ProcSubst:
// avoid conflict with << and others
if p.wantSpace == spaceRequired {
p.space()
}
p.WriteString(x.Op.String())
p.nestedStmts(x.Stmts, x.Last, x.Rparen)
p.rightParen(x.Rparen)
}
}
func (p *Printer) dblQuoted(dq *DblQuoted) {
if dq.Dollar {
p.WriteByte('$')
}
p.WriteByte('"')
if len(dq.Parts) > 0 {
p.wordParts(dq.Parts, true)
}
// Add any trailing escaped newlines.
for p.line < dq.Right.Line() {
p.WriteString("\\\n")
p.line++
}
p.WriteByte('"')
}
func (p *Printer) wroteIndex(index ArithmExpr) bool {
if index == nil {
return false
}
p.WriteByte('[')
p.arithmExpr(index, false, false)
p.WriteByte(']')
return true
}
func (p *Printer) paramExp(pe *ParamExp) {
if pe.nakedIndex() { // arr[x]
p.writeLit(pe.Param.Value)
p.wroteIndex(pe.Index)
return
}
if pe.Short { // $var
p.WriteByte('$')
p.writeLit(pe.Param.Value)
return
}
// ${var...}
p.WriteString("${")
switch {
case pe.Length:
p.WriteByte('#')
case pe.Width:
p.WriteByte('%')
case pe.Excl:
p.WriteByte('!')
}
p.writeLit(pe.Param.Value)
p.wroteIndex(pe.Index)
switch {
case pe.Slice != nil:
p.WriteByte(':')
p.arithmExpr(pe.Slice.Offset, true, true)
if pe.Slice.Length != nil {
p.WriteByte(':')
p.arithmExpr(pe.Slice.Length, true, false)
}
case pe.Repl != nil:
if pe.Repl.All {
p.WriteByte('/')
}
p.WriteByte('/')
if pe.Repl.Orig != nil {
p.word(pe.Repl.Orig)
}
p.WriteByte('/')
if pe.Repl.With != nil {
p.word(pe.Repl.With)
}
case pe.Names != 0:
p.writeLit(pe.Names.String())
case pe.Exp != nil:
p.WriteString(pe.Exp.Op.String())
if pe.Exp.Word != nil {
p.word(pe.Exp.Word)
}
}
p.WriteByte('}')
}
func (p *Printer) loop(loop Loop) {
switch x := loop.(type) {
case *WordIter:
p.writeLit(x.Name.Value)
if x.InPos.IsValid() {
p.spacedString(" in", Pos{})
p.wordJoin(x.Items)
}
case *CStyleLoop:
p.WriteString("((")
if x.Init == nil {
p.space()
}
p.arithmExpr(x.Init, false, false)
p.WriteString("; ")
p.arithmExpr(x.Cond, false, false)
p.WriteString("; ")
p.arithmExpr(x.Post, false, false)
p.WriteString("))")
}
}
func (p *Printer) arithmExpr(expr ArithmExpr, compact, spacePlusMinus bool) {
if p.minify {
compact = true
}
switch x := expr.(type) {
case *Word:
p.word(x)
case *BinaryArithm:
if compact {
p.arithmExpr(x.X, compact, spacePlusMinus)
p.WriteString(x.Op.String())
p.arithmExpr(x.Y, compact, false)
} else {
p.arithmExpr(x.X, compact, spacePlusMinus)
if x.Op != Comma {
p.space()
}
p.WriteString(x.Op.String())
p.space()
p.arithmExpr(x.Y, compact, false)
}
case *UnaryArithm:
if x.Post {
p.arithmExpr(x.X, compact, spacePlusMinus)
p.WriteString(x.Op.String())
} else {
if spacePlusMinus {
switch x.Op {
case Plus, Minus:
p.space()
}
}
p.WriteString(x.Op.String())
p.arithmExpr(x.X, compact, false)
}
case *ParenArithm:
p.WriteByte('(')
p.arithmExpr(x.X, false, false)
p.WriteByte(')')
}
}
func (p *Printer) testExpr(expr TestExpr) {
// Multi-line test expressions don't need to escape newlines.
if expr.Pos().Line() > p.line {
p.newlines(expr.Pos())
p.spacePad(expr.Pos())
} else if p.wantSpace == spaceRequired {
p.space()
}
p.testExprSameLine(expr)
}
func (p *Printer) testExprSameLine(expr TestExpr) {
p.advanceLine(expr.Pos().Line())
switch x := expr.(type) {
case *Word:
p.word(x)
case *BinaryTest:
p.testExprSameLine(x.X)
p.space()
p.WriteString(x.Op.String())
switch x.Op {
case AndTest, OrTest:
p.wantSpace = spaceRequired
p.testExpr(x.Y)
default:
p.space()
p.testExprSameLine(x.Y)
}
case *UnaryTest:
p.WriteString(x.Op.String())
p.space()
p.testExprSameLine(x.X)
case *ParenTest:
p.WriteByte('(')
if startsWithLparen(x.X) {
p.wantSpace = spaceRequired
} else {
p.wantSpace = spaceNotRequired
}
p.testExpr(x.X)
p.WriteByte(')')
}
}
func (p *Printer) word(w *Word) {
p.wordParts(w.Parts, false)
p.wantSpace = spaceRequired
}
func (p *Printer) unquotedWord(w *Word) {
for _, wp := range w.Parts {
switch x := wp.(type) {
case *SglQuoted:
p.writeLit(x.Value)
case *DblQuoted:
p.wordParts(x.Parts, true)
case *Lit:
for i := 0; i < len(x.Value); i++ {
if b := x.Value[i]; b == '\\' {
if i++; i < len(x.Value) {
p.WriteByte(x.Value[i])
}
} else {
p.WriteByte(b)
}
}
}
}
}
func (p *Printer) wordJoin(ws []*Word) {
anyNewline := false
for _, w := range ws {
if pos := w.Pos(); pos.Line() > p.line && !p.singleLine {
if !anyNewline {
p.incLevel()
anyNewline = true
}
p.bslashNewl()
}
p.spacePad(w.Pos())
p.word(w)
}
if anyNewline {
p.decLevel()
}
}
func (p *Printer) casePatternJoin(pats []*Word) {
anyNewline := false
for i, w := range pats {
if i > 0 {
p.spacedToken("|", Pos{})
}
if p.wantsNewline(w.Pos(), true) {
if !anyNewline {
p.incLevel()
anyNewline = true
}
p.bslashNewl()
} else {
p.spacePad(w.Pos())
}
p.word(w)
}
if anyNewline {
p.decLevel()
}
}
func (p *Printer) elemJoin(elems []*ArrayElem, last []Comment) {
p.incLevel()
for _, el := range elems {
var left []Comment
for _, c := range el.Comments {
if c.Pos().After(el.Pos()) {
left = append(left, c)
break
}
p.comments(c)
}
// Multi-line array expressions don't need to escape newlines.
if el.Pos().Line() > p.line {
p.newlines(el.Pos())
p.spacePad(el.Pos())
} else if p.wantSpace == spaceRequired {
p.space()
}
if p.wroteIndex(el.Index) {
p.WriteByte('=')
}
if el.Value != nil {
p.word(el.Value)
}