Source file
src/go/printer/printer.go
1
2
3
4
5
6 package printer
7
8 import (
9 "fmt"
10 "go/ast"
11 "go/build/constraint"
12 "go/token"
13 "io"
14 "os"
15 "strings"
16 "sync"
17 "text/tabwriter"
18 "unicode"
19 )
20
21 const (
22 maxNewlines = 2
23 debug = false
24 infinity = 1 << 30
25 )
26
27 type whiteSpace byte
28
29 const (
30 ignore = whiteSpace(0)
31 blank = whiteSpace(' ')
32 vtab = whiteSpace('\v')
33 newline = whiteSpace('\n')
34 formfeed = whiteSpace('\f')
35 indent = whiteSpace('>')
36 unindent = whiteSpace('<')
37 )
38
39
40 type pmode int
41
42 const (
43 noExtraBlank pmode = 1 << iota
44 noExtraLinebreak
45 )
46
47 type commentInfo struct {
48 cindex int
49 comment *ast.CommentGroup
50 commentOffset int
51 commentNewline bool
52 }
53
54 type printer struct {
55
56 Config
57 fset *token.FileSet
58
59
60 output []byte
61 indent int
62 level int
63 mode pmode
64 endAlignment bool
65 impliedSemi bool
66 lastTok token.Token
67 prevOpen token.Token
68 wsbuf []whiteSpace
69 goBuild []int
70 plusBuild []int
71
72
73
74
75
76
77
78 pos token.Position
79 out token.Position
80 last token.Position
81 linePtr *int
82 sourcePosErr error
83
84
85 comments []*ast.CommentGroup
86 useNodeComments bool
87
88
89 commentInfo
90
91
92 nodeSizes map[ast.Node]int
93
94
95 cachedPos token.Pos
96 cachedLine int
97 }
98
99 func (p *printer) internalError(msg ...any) {
100 if debug {
101 fmt.Print(p.pos.String() + ": ")
102 fmt.Println(msg...)
103 panic("go/printer")
104 }
105 }
106
107
108
109
110 func (p *printer) commentsHaveNewline(list []*ast.Comment) bool {
111
112 line := p.lineFor(list[0].Pos())
113 for i, c := range list {
114 if i > 0 && p.lineFor(list[i].Pos()) != line {
115
116 return true
117 }
118 if t := c.Text; len(t) >= 2 && (t[1] == '/' || strings.Contains(t, "\n")) {
119 return true
120 }
121 }
122 _ = line
123 return false
124 }
125
126 func (p *printer) nextComment() {
127 for p.cindex < len(p.comments) {
128 c := p.comments[p.cindex]
129 p.cindex++
130 if list := c.List; len(list) > 0 {
131 p.comment = c
132 p.commentOffset = p.posFor(list[0].Pos()).Offset
133 p.commentNewline = p.commentsHaveNewline(list)
134 return
135 }
136
137
138 }
139
140 p.commentOffset = infinity
141 }
142
143
144
145
146 func (p *printer) commentBefore(next token.Position) bool {
147 return p.commentOffset < next.Offset && (!p.impliedSemi || !p.commentNewline)
148 }
149
150
151
152 func (p *printer) commentSizeBefore(next token.Position) int {
153
154 defer func(info commentInfo) {
155 p.commentInfo = info
156 }(p.commentInfo)
157
158 size := 0
159 for p.commentBefore(next) {
160 for _, c := range p.comment.List {
161 size += len(c.Text)
162 }
163 p.nextComment()
164 }
165 return size
166 }
167
168
169
170
171
172 func (p *printer) recordLine(linePtr *int) {
173 p.linePtr = linePtr
174 }
175
176
177
178
179
180 func (p *printer) linesFrom(line int) int {
181 return p.out.Line - line
182 }
183
184 func (p *printer) posFor(pos token.Pos) token.Position {
185
186 return p.fset.PositionFor(pos, false )
187 }
188
189 func (p *printer) lineFor(pos token.Pos) int {
190 if pos != p.cachedPos {
191 p.cachedPos = pos
192 p.cachedLine = p.fset.PositionFor(pos, false ).Line
193 }
194 return p.cachedLine
195 }
196
197
198 func (p *printer) writeLineDirective(pos token.Position) {
199 if pos.IsValid() && (p.out.Line != pos.Line || p.out.Filename != pos.Filename) {
200 if strings.ContainsAny(pos.Filename, "\r\n") {
201 if p.sourcePosErr == nil {
202 p.sourcePosErr = fmt.Errorf("go/printer: source filename contains unexpected newline character: %q", pos.Filename)
203 }
204 return
205 }
206
207 p.output = append(p.output, tabwriter.Escape)
208 p.output = append(p.output, fmt.Sprintf("//line %s:%d\n", pos.Filename, pos.Line)...)
209 p.output = append(p.output, tabwriter.Escape)
210
211 p.out.Filename = pos.Filename
212 p.out.Line = pos.Line
213 }
214 }
215
216
217 func (p *printer) writeIndent() {
218
219
220 n := p.Config.Indent + p.indent
221 for i := 0; i < n; i++ {
222 p.output = append(p.output, '\t')
223 }
224
225
226 p.pos.Offset += n
227 p.pos.Column += n
228 p.out.Column += n
229 }
230
231
232
233 func (p *printer) writeByte(ch byte, n int) {
234 if p.endAlignment {
235
236
237
238
239 switch ch {
240 case '\t', '\v':
241 ch = ' '
242 case '\n', '\f':
243 ch = '\f'
244 p.endAlignment = false
245 }
246 }
247
248 if p.out.Column == 1 {
249
250 p.writeIndent()
251 }
252
253 for i := 0; i < n; i++ {
254 p.output = append(p.output, ch)
255 }
256
257
258 p.pos.Offset += n
259 if ch == '\n' || ch == '\f' {
260 p.pos.Line += n
261 p.out.Line += n
262 p.pos.Column = 1
263 p.out.Column = 1
264 return
265 }
266 p.pos.Column += n
267 p.out.Column += n
268 }
269
270
271
272
273
274
275
276
277
278
279
280 func (p *printer) writeString(pos token.Position, s string, isLit bool) {
281 if p.out.Column == 1 {
282 if p.Config.Mode&SourcePos != 0 {
283 p.writeLineDirective(pos)
284 }
285 p.writeIndent()
286 }
287
288 if pos.IsValid() {
289
290
291
292
293 p.pos = pos
294 }
295
296 if isLit {
297
298
299
300
301 p.output = append(p.output, tabwriter.Escape)
302 }
303
304 if debug {
305 p.output = append(p.output, fmt.Sprintf("/*%s*/", pos)...)
306 }
307 p.output = append(p.output, s...)
308
309
310 nlines := 0
311 var li int
312 for i := 0; i < len(s); i++ {
313
314 if ch := s[i]; ch == '\n' || ch == '\f' {
315
316 nlines++
317 li = i
318
319
320
321 p.endAlignment = true
322 }
323 }
324 p.pos.Offset += len(s)
325 if nlines > 0 {
326 p.pos.Line += nlines
327 p.out.Line += nlines
328 c := len(s) - li
329 p.pos.Column = c
330 p.out.Column = c
331 } else {
332 p.pos.Column += len(s)
333 p.out.Column += len(s)
334 }
335
336 if isLit {
337 p.output = append(p.output, tabwriter.Escape)
338 }
339
340 p.last = p.pos
341 }
342
343
344
345
346
347
348
349 func (p *printer) writeCommentPrefix(pos, next token.Position, prev *ast.Comment, tok token.Token) {
350 if len(p.output) == 0 {
351
352 return
353 }
354
355 if pos.IsValid() && pos.Filename != p.last.Filename {
356
357 p.writeByte('\f', maxNewlines)
358 return
359 }
360
361 if pos.Line == p.last.Line && (prev == nil || prev.Text[1] != '/') {
362
363
364 hasSep := false
365 if prev == nil {
366
367 j := 0
368 for i, ch := range p.wsbuf {
369 switch ch {
370 case blank:
371
372 p.wsbuf[i] = ignore
373 continue
374 case vtab:
375
376
377 hasSep = true
378 continue
379 case indent:
380
381 continue
382 }
383 j = i
384 break
385 }
386 p.writeWhitespace(j)
387 }
388
389 if !hasSep {
390 sep := byte('\t')
391 if pos.Line == next.Line {
392
393
394
395 sep = ' '
396 }
397 p.writeByte(sep, 1)
398 }
399
400 } else {
401
402
403 droppedLinebreak := false
404 j := 0
405 for i, ch := range p.wsbuf {
406 switch ch {
407 case blank, vtab:
408
409 p.wsbuf[i] = ignore
410 continue
411 case indent:
412
413 continue
414 case unindent:
415
416
417
418
419 if i+1 < len(p.wsbuf) && p.wsbuf[i+1] == unindent {
420 continue
421 }
422
423
424
425
426
427
428 if tok != token.RBRACE && pos.Column == next.Column {
429 continue
430 }
431 case newline, formfeed:
432 p.wsbuf[i] = ignore
433 droppedLinebreak = prev == nil
434 }
435 j = i
436 break
437 }
438 p.writeWhitespace(j)
439
440
441 n := 0
442 if pos.IsValid() && p.last.IsValid() {
443 n = pos.Line - p.last.Line
444 if n < 0 {
445 n = 0
446 }
447 }
448
449
450
451
452
453 if p.indent == 0 && droppedLinebreak {
454 n++
455 }
456
457
458
459 if n == 0 && prev != nil && prev.Text[1] == '/' {
460 n = 1
461 }
462
463 if n > 0 {
464
465
466
467 p.writeByte('\f', nlimit(n))
468 }
469 }
470 }
471
472
473
474 func isBlank(s string) bool {
475 for i := 0; i < len(s); i++ {
476 if s[i] > ' ' {
477 return false
478 }
479 }
480 return true
481 }
482
483
484 func commonPrefix(a, b string) string {
485 i := 0
486 for i < len(a) && i < len(b) && a[i] == b[i] && (a[i] <= ' ' || a[i] == '*') {
487 i++
488 }
489 return a[0:i]
490 }
491
492
493 func trimRight(s string) string {
494 return strings.TrimRightFunc(s, unicode.IsSpace)
495 }
496
497
498
499
500
501
502 func stripCommonPrefix(lines []string) {
503 if len(lines) <= 1 {
504 return
505 }
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527 prefix := ""
528 prefixSet := false
529 if len(lines) > 2 {
530 for i, line := range lines[1 : len(lines)-1] {
531 if isBlank(line) {
532 lines[1+i] = ""
533 } else {
534 if !prefixSet {
535 prefix = line
536 prefixSet = true
537 }
538 prefix = commonPrefix(prefix, line)
539 }
540
541 }
542 }
543
544 if !prefixSet {
545 line := lines[len(lines)-1]
546 prefix = commonPrefix(line, line)
547 }
548
549
552 lineOfStars := false
553 if p, _, ok := strings.Cut(prefix, "*"); ok {
554
555 prefix = strings.TrimSuffix(p, " ")
556 lineOfStars = true
557 } else {
558
559
560
561
562
563
564
565 first := lines[0]
566 if isBlank(first[2:]) {
567
568
569
570
571
572 i := len(prefix)
573 for n := 0; n < 3 && i > 0 && prefix[i-1] == ' '; n++ {
574 i--
575 }
576 if i == len(prefix) && i > 0 && prefix[i-1] == '\t' {
577 i--
578 }
579 prefix = prefix[0:i]
580 } else {
581
582 suffix := make([]byte, len(first))
583 n := 2
584 for n < len(first) && first[n] <= ' ' {
585 suffix[n] = first[n]
586 n++
587 }
588 if n > 2 && suffix[2] == '\t' {
589
590 suffix = suffix[2:n]
591 } else {
592
593 suffix[0], suffix[1] = ' ', ' '
594 suffix = suffix[0:n]
595 }
596
597
598 prefix = strings.TrimSuffix(prefix, string(suffix))
599 }
600 }
601
602
603
604
605 last := lines[len(lines)-1]
606 closing := "*/"
607 before, _, _ := strings.Cut(last, closing)
608 if isBlank(before) {
609
610 if lineOfStars {
611 closing = " */"
612 }
613 lines[len(lines)-1] = prefix + closing
614 } else {
615
616
617
618 prefix = commonPrefix(prefix, last)
619 }
620
621
622 for i, line := range lines {
623 if i > 0 && line != "" {
624 lines[i] = line[len(prefix):]
625 }
626 }
627 }
628
629 func (p *printer) writeComment(comment *ast.Comment) {
630 text := comment.Text
631 pos := p.posFor(comment.Pos())
632
633 const linePrefix = "//line "
634 if strings.HasPrefix(text, linePrefix) && (!pos.IsValid() || pos.Column == 1) {
635
636
637 defer func(indent int) { p.indent = indent }(p.indent)
638 p.indent = 0
639 }
640
641
642 if text[1] == '/' {
643 if constraint.IsGoBuild(text) {
644 p.goBuild = append(p.goBuild, len(p.output))
645 } else if constraint.IsPlusBuild(text) {
646 p.plusBuild = append(p.plusBuild, len(p.output))
647 }
648 p.writeString(pos, trimRight(text), true)
649 return
650 }
651
652
653
654 lines := strings.Split(text, "\n")
655
656
657
658
659
660
661
662 if pos.IsValid() && pos.Column == 1 && p.indent > 0 {
663 for i, line := range lines[1:] {
664 lines[1+i] = " " + line
665 }
666 }
667
668 stripCommonPrefix(lines)
669
670
671
672 for i, line := range lines {
673 if i > 0 {
674 p.writeByte('\f', 1)
675 pos = p.pos
676 }
677 if len(line) > 0 {
678 p.writeString(pos, trimRight(line), true)
679 }
680 }
681 }
682
683
684
685
686
687
688
689 func (p *printer) writeCommentSuffix(needsLinebreak bool) (wroteNewline, droppedFF bool) {
690 for i, ch := range p.wsbuf {
691 switch ch {
692 case blank, vtab:
693
694 p.wsbuf[i] = ignore
695 case indent, unindent:
696
697 case newline, formfeed:
698
699
700 if needsLinebreak {
701 needsLinebreak = false
702 wroteNewline = true
703 } else {
704 if ch == formfeed {
705 droppedFF = true
706 }
707 p.wsbuf[i] = ignore
708 }
709 }
710 }
711 p.writeWhitespace(len(p.wsbuf))
712
713
714 if needsLinebreak {
715 p.writeByte('\n', 1)
716 wroteNewline = true
717 }
718
719 return
720 }
721
722
723 func (p *printer) containsLinebreak() bool {
724 for _, ch := range p.wsbuf {
725 if ch == newline || ch == formfeed {
726 return true
727 }
728 }
729 return false
730 }
731
732
733
734
735
736
737 func (p *printer) intersperseComments(next token.Position, tok token.Token) (wroteNewline, droppedFF bool) {
738 var last *ast.Comment
739 for p.commentBefore(next) {
740 list := p.comment.List
741 changed := false
742
743 if tok != token.IDENT &&
744 p.lastTok != token.IMPORT &&
745 p.posFor(p.comment.Pos()).Column == 1 &&
746 p.posFor(p.comment.End()+1) == next {
747
748
749 list = formatDocComment(list)
750 changed = true
751
752 if len(p.comment.List) > 0 && len(list) == 0 {
753
754
755 p.writeCommentPrefix(p.posFor(p.comment.Pos()), next, last, tok)
756
757 p.pos = next
758 p.last = next
759
760 p.nextComment()
761 return p.writeCommentSuffix(false)
762 }
763 }
764 for _, c := range list {
765 p.writeCommentPrefix(p.posFor(c.Pos()), next, last, tok)
766 p.writeComment(c)
767 last = c
768 }
769
770
771 if len(p.comment.List) > 0 && changed {
772 last = p.comment.List[len(p.comment.List)-1]
773 p.pos = p.posFor(last.End())
774 p.last = p.pos
775 }
776 p.nextComment()
777 }
778
779 if last != nil {
780
781
782
783
784
785
786
787
788
789
790 needsLinebreak := false
791 if p.mode&noExtraBlank == 0 &&
792 last.Text[1] == '*' && p.lineFor(last.Pos()) == next.Line &&
793 tok != token.COMMA &&
794 (tok != token.RPAREN || p.prevOpen == token.LPAREN) &&
795 (tok != token.RBRACK || p.prevOpen == token.LBRACK) {
796 if p.containsLinebreak() && p.mode&noExtraLinebreak == 0 && p.level == 0 {
797 needsLinebreak = true
798 } else {
799 p.writeByte(' ', 1)
800 }
801 }
802
803
804 if last.Text[1] == '/' ||
805 tok == token.EOF ||
806 tok == token.RBRACE && p.mode&noExtraLinebreak == 0 {
807 needsLinebreak = true
808 }
809 return p.writeCommentSuffix(needsLinebreak)
810 }
811
812
813
814 p.internalError("intersperseComments called without pending comments")
815 return
816 }
817
818
819 func (p *printer) writeWhitespace(n int) {
820
821 for i := 0; i < n; i++ {
822 switch ch := p.wsbuf[i]; ch {
823 case ignore:
824
825 case indent:
826 p.indent++
827 case unindent:
828 p.indent--
829 if p.indent < 0 {
830 p.internalError("negative indentation:", p.indent)
831 p.indent = 0
832 }
833 case newline, formfeed:
834
835
836
837
838
839
840 if i+1 < n && p.wsbuf[i+1] == unindent {
841
842
843
844
845
846 p.wsbuf[i], p.wsbuf[i+1] = unindent, formfeed
847 i--
848 continue
849 }
850 fallthrough
851 default:
852 p.writeByte(byte(ch), 1)
853 }
854 }
855
856
857 l := copy(p.wsbuf, p.wsbuf[n:])
858 p.wsbuf = p.wsbuf[:l]
859 }
860
861
862
863
864
865 func nlimit(n int) int {
866 return min(n, maxNewlines)
867 }
868
869 func mayCombine(prev token.Token, next byte) (b bool) {
870 switch prev {
871 case token.INT:
872 b = next == '.'
873 case token.ADD:
874 b = next == '+'
875 case token.SUB:
876 b = next == '-'
877 case token.QUO:
878 b = next == '*'
879 case token.LSS:
880 b = next == '-' || next == '<'
881 case token.AND:
882 b = next == '&' || next == '^'
883 }
884 return
885 }
886
887 func (p *printer) setPos(pos token.Pos) {
888 if pos.IsValid() {
889 p.pos = p.posFor(pos)
890 }
891 }
892
893
894
895
896
897
898
899
900
901
902
903 func (p *printer) print(args ...any) {
904 for _, arg := range args {
905
906 var data string
907 var isLit bool
908 var impliedSemi bool
909
910
911 switch p.lastTok {
912 case token.ILLEGAL:
913
914 case token.LPAREN, token.LBRACK:
915 p.prevOpen = p.lastTok
916 default:
917
918 p.prevOpen = token.ILLEGAL
919 }
920
921 switch x := arg.(type) {
922 case pmode:
923
924 p.mode ^= x
925 continue
926
927 case whiteSpace:
928 if x == ignore {
929
930
931
932 continue
933 }
934 i := len(p.wsbuf)
935 if i == cap(p.wsbuf) {
936
937
938
939 p.writeWhitespace(i)
940 i = 0
941 }
942 p.wsbuf = p.wsbuf[0 : i+1]
943 p.wsbuf[i] = x
944 if x == newline || x == formfeed {
945
946
947
948
949 p.impliedSemi = false
950 }
951 p.lastTok = token.ILLEGAL
952 continue
953
954 case *ast.Ident:
955 data = x.Name
956 impliedSemi = true
957 p.lastTok = token.IDENT
958
959 case *ast.BasicLit:
960 data = x.Value
961 isLit = true
962 impliedSemi = true
963 p.lastTok = x.Kind
964
965 case token.Token:
966 s := x.String()
967 if mayCombine(p.lastTok, s[0]) {
968
969
970
971
972
973
974 if len(p.wsbuf) != 0 {
975 p.internalError("whitespace buffer not empty")
976 }
977 p.wsbuf = p.wsbuf[0:1]
978 p.wsbuf[0] = ' '
979 }
980 data = s
981
982 switch x {
983 case token.BREAK, token.CONTINUE, token.FALLTHROUGH, token.RETURN,
984 token.INC, token.DEC, token.RPAREN, token.RBRACK, token.RBRACE:
985 impliedSemi = true
986 }
987 p.lastTok = x
988
989 case string:
990
991 data = x
992 isLit = true
993 impliedSemi = true
994 p.lastTok = token.STRING
995
996 default:
997 fmt.Fprintf(os.Stderr, "print: unsupported argument %v (%T)\n", arg, arg)
998 panic("go/printer type")
999 }
1000
1001
1002 next := p.pos
1003 wroteNewline, droppedFF := p.flush(next, p.lastTok)
1004
1005
1006
1007
1008 if !p.impliedSemi {
1009 n := nlimit(next.Line - p.pos.Line)
1010
1011 if wroteNewline && n == maxNewlines {
1012 n = maxNewlines - 1
1013 }
1014 if n > 0 {
1015 ch := byte('\n')
1016 if droppedFF {
1017 ch = '\f'
1018 }
1019 p.writeByte(ch, n)
1020 impliedSemi = false
1021 }
1022 }
1023
1024
1025 if p.linePtr != nil {
1026 *p.linePtr = p.out.Line
1027 p.linePtr = nil
1028 }
1029
1030 p.writeString(next, data, isLit)
1031 p.impliedSemi = impliedSemi
1032 }
1033 }
1034
1035
1036
1037
1038
1039 func (p *printer) flush(next token.Position, tok token.Token) (wroteNewline, droppedFF bool) {
1040 if p.commentBefore(next) {
1041
1042 wroteNewline, droppedFF = p.intersperseComments(next, tok)
1043 } else {
1044
1045 p.writeWhitespace(len(p.wsbuf))
1046 }
1047 return
1048 }
1049
1050
1051 func getDoc(n ast.Node) *ast.CommentGroup {
1052 switch n := n.(type) {
1053 case *ast.Field:
1054 return n.Doc
1055 case *ast.ImportSpec:
1056 return n.Doc
1057 case *ast.ValueSpec:
1058 return n.Doc
1059 case *ast.TypeSpec:
1060 return n.Doc
1061 case *ast.GenDecl:
1062 return n.Doc
1063 case *ast.FuncDecl:
1064 return n.Doc
1065 case *ast.File:
1066 return n.Doc
1067 }
1068 return nil
1069 }
1070
1071 func getLastComment(n ast.Node) *ast.CommentGroup {
1072 switch n := n.(type) {
1073 case *ast.Field:
1074 return n.Comment
1075 case *ast.ImportSpec:
1076 return n.Comment
1077 case *ast.ValueSpec:
1078 return n.Comment
1079 case *ast.TypeSpec:
1080 return n.Comment
1081 case *ast.GenDecl:
1082 if len(n.Specs) > 0 {
1083 return getLastComment(n.Specs[len(n.Specs)-1])
1084 }
1085 case *ast.File:
1086 if len(n.Comments) > 0 {
1087 return n.Comments[len(n.Comments)-1]
1088 }
1089 }
1090 return nil
1091 }
1092
1093 func (p *printer) printNode(node any) error {
1094
1095 var comments []*ast.CommentGroup
1096 if cnode, ok := node.(*CommentedNode); ok {
1097 node = cnode.Node
1098 comments = cnode.Comments
1099 }
1100
1101 if comments != nil {
1102
1103 n, ok := node.(ast.Node)
1104 if !ok {
1105 goto unsupported
1106 }
1107 beg := n.Pos()
1108 end := n.End()
1109
1110
1111
1112
1113 if doc := getDoc(n); doc != nil {
1114 beg = doc.Pos()
1115 }
1116 if com := getLastComment(n); com != nil {
1117 if e := com.End(); e > end {
1118 end = e
1119 }
1120 }
1121
1122
1123 i := 0
1124 for i < len(comments) && comments[i].End() < beg {
1125 i++
1126 }
1127 j := i
1128 for j < len(comments) && comments[j].Pos() < end {
1129 j++
1130 }
1131 if i < j {
1132 p.comments = comments[i:j]
1133 }
1134 } else if n, ok := node.(*ast.File); ok {
1135
1136 p.comments = n.Comments
1137 }
1138
1139
1140 p.useNodeComments = p.comments == nil
1141
1142
1143 p.nextComment()
1144
1145 p.print(pmode(0))
1146
1147
1148 switch n := node.(type) {
1149 case ast.Expr:
1150 p.expr(n)
1151 case ast.Stmt:
1152
1153
1154 if _, ok := n.(*ast.LabeledStmt); ok {
1155 p.indent = 1
1156 }
1157 p.stmt(n, false)
1158 case ast.Decl:
1159 p.decl(n)
1160 case ast.Spec:
1161 p.spec(n, 1, false)
1162 case []ast.Stmt:
1163
1164
1165 for _, s := range n {
1166 if _, ok := s.(*ast.LabeledStmt); ok {
1167 p.indent = 1
1168 }
1169 }
1170 p.stmtList(n, 0, false)
1171 case []ast.Decl:
1172 p.declList(n)
1173 case *ast.File:
1174 p.file(n)
1175 default:
1176 goto unsupported
1177 }
1178
1179 return p.sourcePosErr
1180
1181 unsupported:
1182 return fmt.Errorf("go/printer: unsupported node type %T", node)
1183 }
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193 type trimmer struct {
1194 output io.Writer
1195 state int
1196 space []byte
1197 }
1198
1199
1200
1201 const (
1202 inSpace = iota
1203 inEscape
1204 inText
1205 )
1206
1207 func (p *trimmer) resetSpace() {
1208 p.state = inSpace
1209 p.space = p.space[0:0]
1210 }
1211
1212
1213
1214
1215
1216
1217
1218 var aNewline = []byte("\n")
1219
1220 func (p *trimmer) Write(data []byte) (n int, err error) {
1221
1222
1223
1224
1225
1226 m := 0
1227 var b byte
1228 for n, b = range data {
1229 if b == '\v' {
1230 b = '\t'
1231 }
1232 switch p.state {
1233 case inSpace:
1234 switch b {
1235 case '\t', ' ':
1236 p.space = append(p.space, b)
1237 case '\n', '\f':
1238 p.resetSpace()
1239 _, err = p.output.Write(aNewline)
1240 case tabwriter.Escape:
1241 _, err = p.output.Write(p.space)
1242 p.state = inEscape
1243 m = n + 1
1244 default:
1245 _, err = p.output.Write(p.space)
1246 p.state = inText
1247 m = n
1248 }
1249 case inEscape:
1250 if b == tabwriter.Escape {
1251 _, err = p.output.Write(data[m:n])
1252 p.resetSpace()
1253 }
1254 case inText:
1255 switch b {
1256 case '\t', ' ':
1257 _, err = p.output.Write(data[m:n])
1258 p.resetSpace()
1259 p.space = append(p.space, b)
1260 case '\n', '\f':
1261 _, err = p.output.Write(data[m:n])
1262 p.resetSpace()
1263 if err == nil {
1264 _, err = p.output.Write(aNewline)
1265 }
1266 case tabwriter.Escape:
1267 _, err = p.output.Write(data[m:n])
1268 p.state = inEscape
1269 m = n + 1
1270 }
1271 default:
1272 panic("unreachable")
1273 }
1274 if err != nil {
1275 return
1276 }
1277 }
1278 n = len(data)
1279
1280 switch p.state {
1281 case inEscape, inText:
1282 _, err = p.output.Write(data[m:n])
1283 p.resetSpace()
1284 }
1285
1286 return
1287 }
1288
1289
1290
1291
1292
1293 type Mode uint
1294
1295 const (
1296 RawFormat Mode = 1 << iota
1297 TabIndent
1298 UseSpaces
1299 SourcePos
1300 )
1301
1302
1303
1304
1305
1306
1307 const (
1308
1309
1310
1311
1312
1313
1314
1315 normalizeNumbers Mode = 1 << 30
1316 )
1317
1318
1319 type Config struct {
1320 Mode Mode
1321 Tabwidth int
1322 Indent int
1323 }
1324
1325 var printerPool = sync.Pool{
1326 New: func() any {
1327 return &printer{
1328
1329 wsbuf: make([]whiteSpace, 0, 16),
1330
1331
1332 output: make([]byte, 0, 16<<10),
1333 }
1334 },
1335 }
1336
1337 func newPrinter(cfg *Config, fset *token.FileSet, nodeSizes map[ast.Node]int) *printer {
1338 p := printerPool.Get().(*printer)
1339 *p = printer{
1340 Config: *cfg,
1341 fset: fset,
1342 pos: token.Position{Line: 1, Column: 1},
1343 out: token.Position{Line: 1, Column: 1},
1344 wsbuf: p.wsbuf[:0],
1345 nodeSizes: nodeSizes,
1346 cachedPos: -1,
1347 output: p.output[:0],
1348 }
1349 return p
1350 }
1351
1352 func (p *printer) free() {
1353
1354 if cap(p.output) > 64<<10 {
1355 return
1356 }
1357
1358 printerPool.Put(p)
1359 }
1360
1361
1362 func (cfg *Config) fprint(output io.Writer, fset *token.FileSet, node any, nodeSizes map[ast.Node]int) (err error) {
1363
1364 p := newPrinter(cfg, fset, nodeSizes)
1365 defer p.free()
1366 if err = p.printNode(node); err != nil {
1367 return
1368 }
1369
1370 p.impliedSemi = false
1371 p.flush(token.Position{Offset: infinity, Line: infinity}, token.EOF)
1372
1373
1374
1375 p.fixGoBuildLines()
1376
1377
1378
1379
1380
1381 output = &trimmer{output: output}
1382
1383
1384 if cfg.Mode&RawFormat == 0 {
1385 minwidth := cfg.Tabwidth
1386
1387 padchar := byte('\t')
1388 if cfg.Mode&UseSpaces != 0 {
1389 padchar = ' '
1390 }
1391
1392 twmode := tabwriter.DiscardEmptyColumns
1393 if cfg.Mode&TabIndent != 0 {
1394 minwidth = 0
1395 twmode |= tabwriter.TabIndent
1396 }
1397
1398 output = tabwriter.NewWriter(output, minwidth, cfg.Tabwidth, 1, padchar, twmode)
1399 }
1400
1401
1402 if _, err = output.Write(p.output); err != nil {
1403 return
1404 }
1405
1406
1407 if tw, _ := output.(*tabwriter.Writer); tw != nil {
1408 err = tw.Flush()
1409 }
1410
1411 return
1412 }
1413
1414
1415
1416 type CommentedNode struct {
1417 Node any
1418 Comments []*ast.CommentGroup
1419 }
1420
1421
1422
1423
1424
1425 func (cfg *Config) Fprint(output io.Writer, fset *token.FileSet, node any) error {
1426 return cfg.fprint(output, fset, node, make(map[ast.Node]int))
1427 }
1428
1429
1430
1431
1432
1433 func Fprint(output io.Writer, fset *token.FileSet, node any) error {
1434 return (&Config{Tabwidth: 8}).Fprint(output, fset, node)
1435 }
1436
View as plain text