/
write_comment.go
75 lines (62 loc) · 1.83 KB
/
write_comment.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
package tygo
import (
"go/ast"
"strings"
)
func (g *PackageGenerator) PreserveDocComments() bool {
return g.conf.PreserveComments == "default"
}
func (g *PackageGenerator) PreserveTypeComments() bool {
return g.conf.PreserveComments == "types" || g.conf.PreserveComments == "default"
}
func (g *PackageGenerator) writeCommentGroupIfNotNil(s *strings.Builder, f *ast.CommentGroup, depth int) {
if f != nil {
g.writeCommentGroup(s, f, depth)
}
}
func (c *PackageGenerator) writeDirective(s *strings.Builder, cg *ast.CommentGroup) {
for _, cm := range cg.List {
if strings.HasPrefix(cm.Text, "//tygo:emit") {
// remove the separator whitespace but leave extra whitespace for indentation
s.WriteString(strings.TrimPrefix(cm.Text, "//tygo:emit")[1:])
s.WriteString("\n")
}
}
}
func (g *PackageGenerator) writeCommentGroup(s *strings.Builder, cg *ast.CommentGroup, depth int) {
docLines := strings.Split(cg.Text(), "\n")
g.writeDirective(s, cg)
if len(cg.List) > 0 && cg.Text() == "" { // This is a directive comment like //go:embed
s.WriteByte('\n')
return
}
if depth != 0 {
g.writeIndent(s, depth)
}
s.WriteString("/**\n")
for _, c := range docLines {
if len(strings.TrimSpace(c)) == 0 {
continue
}
g.writeIndent(s, depth)
s.WriteString(" * ")
c = strings.ReplaceAll(c, "*/", "*\\/") // An edge case: a // comment can contain */
s.WriteString(c)
s.WriteByte('\n')
}
g.writeIndent(s, depth)
s.WriteString(" */\n")
}
// Outputs a comment like // hello world
func (g *PackageGenerator) writeSingleLineComment(s *strings.Builder, cg *ast.CommentGroup) {
text := cg.Text()
if len(cg.List) > 0 && cg.Text() == "" { // This is a directive comment like //go:embed
s.WriteByte('\n')
return
}
s.WriteString(" // " + text)
if len(text) == 0 {
// This is an empty comment like //
s.WriteByte('\n')
}
}