Debian Codegraph @

write_toplevel.go

raw symbols SCIP
1 package tygoja
2
3 import (
4 "fmt"
5 "go/ast"
6 "strings"
7 )
8
9 type groupContext struct {
10 isGroupedDeclaration bool
11 doc *ast.CommentGroup
12 groupValue string
13 groupType string
14 iotaValue int
15 iotaOffset int
16 }
17
18 // Writing of function declarations, which are expressions like
19 // "func Count() int"
20 // or
21 // "func (s *Counter) total() int"
22 func (g *PackageGenerator) writeFuncDecl(s *strings.Builder, decl *ast.FuncDecl, depth int) {
23 if decl.Name == nil || len(decl.Name.Name) == 0 || decl.Name.Name[0] < 'A' || decl.Name.Name[0] > 'Z' {
24 return // unexported function/method
25 }
26
27 originalMethodName := decl.Name.Name
28 methodName := originalMethodName
29 if g.conf.MethodNameFormatter != nil {
30 methodName = g.conf.MethodNameFormatter(methodName)
31 }
32
33 if decl.Recv == nil {
34 if !g.conf.WithPackageFunctions {
35 return // skip package level functions
36 }
37
38 if !g.isTypeAllowed(originalMethodName) {
39 return
40 } else {
41 g.markTypeAsGenerated(originalMethodName)
42 }
43
44 g.writeStartModifier(s, depth)
45 s.WriteString("interface ")
46
47 if isReservedIdentifier(methodName) {
48 s.WriteString("_" + methodName)
49 } else {
50 s.WriteString(methodName)
51 }
52
53 if decl.Type.TypeParams != nil {
54 g.writeTypeParamsFields(s, decl.Type.TypeParams.List)
55 }
56
57 s.WriteString(" {\n")
58 if decl.Doc != nil {
59 g.writeCommentGroup(s, decl.Doc, depth+1)
60 }
61 g.writeIndent(s, depth+1)
62 g.writeType(s, decl.Type, depth+1)
63 s.WriteString("\n")
64 g.writeIndent(s, depth)
65 s.WriteString("}\n")
66 } else if len(decl.Recv.List) == 1 {
67 // write struct method as new interface method
68 // (note that TS will "merge" the definitions of multiple interfaces with the same name)
69
70 // treat pointer and value receivers the same
71 recvType := decl.Recv.List[0].Type
72 if p, isPointer := recvType.(*ast.StarExpr); isPointer {
73 recvType = p.X
74 }
75
76 var recvName string
77 switch recv := recvType.(type) {
78 case *ast.Ident:
79 recvName = recv.Name
80 case *ast.IndexExpr:
81 if v, ok := recv.X.(*ast.Ident); ok {
82 recvName = v.Name
83 }
84 case *ast.IndexListExpr:
85 if v, ok := recv.X.(*ast.Ident); ok {
86 recvName = v.Name
87 }
88 }
89
90 if !g.isTypeAllowed(recvName) {
91 return
92 } else {
93 g.markTypeAsGenerated(recvName)
94 }
95
96 g.writeStartModifier(s, depth)
97 s.WriteString("interface ")
98
99 g.writeType(s, recvType, depth)
100
101 s.WriteString(" {\n")
102 if decl.Doc != nil {
103 g.writeCommentGroup(s, decl.Doc, depth+1)
104 }
105 g.writeIndent(s, depth+1)
106 s.WriteString(methodName)
107 g.writeType(s, decl.Type, depth+1)
108 s.WriteString("\n")
109 g.writeIndent(s, depth)
110 s.WriteString("}\n")
111 }
112 }
113
114 func (g *PackageGenerator) writeGroupDecl(s *strings.Builder, decl *ast.GenDecl, depth int) {
115 // We need a bit of state to handle syntax like
116 // const (
117 // X SomeType = iota
118 // _
119 // Y
120 // Foo string = "Foo"
121 // _
122 // AlsoFoo
123 // )
124 group := &groupContext{
125 isGroupedDeclaration: len(decl.Specs) > 1,
126 doc: decl.Doc,
127 groupType: "",
128 groupValue: "",
129 iotaValue: -1,
130 }
131
132 for _, spec := range decl.Specs {
133 g.writeSpec(s, spec, group, depth)
134 }
135 }
136
137 func (g *PackageGenerator) writeSpec(s *strings.Builder, spec ast.Spec, group *groupContext, depth int) {
138 // e.g. "type Foo struct {}" or "type Bar = string"
139 ts, ok := spec.(*ast.TypeSpec)
140 if ok {
141 g.writeTypeSpec(s, ts, group, depth)
142 }
143
144 // e.g. "const Foo = 123"
145 vs, ok := spec.(*ast.ValueSpec)
146 if ok && g.conf.WithConstants {
147 g.writeValueSpec(s, vs, group, depth)
148 }
149 }
150
151 // Writing of type specs, which are expressions like
152 // "type X struct { ... }"
153 // or
154 // "type Bar = string"
155 func (g *PackageGenerator) writeTypeSpec(s *strings.Builder, ts *ast.TypeSpec, group *groupContext, depth int) {
156 var typeName string
157 if ts.Name != nil {
158 typeName = ts.Name.Name
159 }
160
161 if !g.isTypeAllowed(typeName) {
162 return
163 } else {
164 g.markTypeAsGenerated(typeName)
165 }
166
167 if ts.Doc != nil {
168 // the spec has its own comment, which overrules the grouped comment
169 g.writeCommentGroup(s, ts.Doc, depth)
170 } else {
171 g.writeCommentGroup(s, group.doc, depth)
172 }
173
174 switch v := ts.Type.(type) {
175 case *ast.StructType:
176 // eg. "type X struct { ... }"
177
178 var extendTypeName string
179
180 // convert embeded structs to "extends SUB_TYPE" declaration
181 //
182 // note: we don't use "extends A, B, C" form but intersecion subtype
183 // with all embeded structs to avoid methods merge conflicts
184 // eg. bufio.ReadWriter has different Writer.Read() and Reader.Read()
185 if v.Fields != nil {
186 var embeds []*ast.Field
187 for _, f := range v.Fields.List {
188 if len(f.Names) == 0 || f.Names[0].Name == "" {
189 embeds = append(embeds, f)
190 }
191 }
192
193 if len(embeds) > 0 {
194 extendTypeName = "_s" + PseudorandomString(6)
195
196 genericArgs := map[string]struct{}{}
197 identSB := new(strings.Builder)
198 embedsSB := new(strings.Builder)
199 for i, f := range embeds {
200 if i > 0 {
201 embedsSB.WriteString("&")
202 }
203
204 typ := f.Type
205 if p, isPointer := typ.(*ast.StarExpr); isPointer {
206 typ = p.X
207 }
208
209 identSB.Reset()
210 g.writeType(identSB, typ, depth, optionParenthesis, optionExtends)
211 ident := identSB.String()
212
213 if idx := strings.Index(ident, "<"); idx > 1 { // has at least 2 characters for <>
214 genericArgs[ident[idx+1:len(ident)-1]] = struct{}{}
215 }
216
217 embedsSB.WriteString(ident)
218 }
219
220 if len(genericArgs) > 0 {
221 args := make([]string, 0, len(genericArgs))
222 for g := range genericArgs {
223 args = append(args, g)
224 }
225 extendTypeName = extendTypeName + "<" + strings.Join(args, ",") + ">"
226 }
227
228 g.writeIndent(s, depth)
229 s.WriteString("type ")
230 s.WriteString(extendTypeName)
231 s.WriteString(" = ")
232 s.WriteString(embedsSB.String())
233 s.WriteString("\n")
234 }
235 }
236
237 g.writeStartModifier(s, depth)
238 s.WriteString("interface ")
239 s.WriteString(typeName)
240
241 if ts.TypeParams != nil {
242 g.writeTypeParamsFields(s, ts.TypeParams.List)
243 }
244
245 if extendTypeName != "" {
246 s.WriteString(" extends ")
247 s.WriteString(extendTypeName)
248 }
249
250 s.WriteString(" {\n")
251 g.writeStructFields(s, v.Fields.List, depth)
252 g.writeIndent(s, depth)
253 s.WriteString("}")
254 case *ast.InterfaceType:
255 // eg. "type X interface { ... }"
256
257 g.writeStartModifier(s, depth)
258 s.WriteString("interface ")
259 s.WriteString(typeName)
260
261 if ts.TypeParams != nil {
262 g.writeTypeParamsFields(s, ts.TypeParams.List)
263 }
264
265 s.WriteString(" {\n")
266
267 // fallback so that it doesn't report an error when attempting
268 // to access a field or method from a struct that implements the interface
269 g.writeIndent(s, depth+1)
270 s.WriteString("[key:string]: any;\n")
271
272 g.writeInterfaceFields(s, v.Methods.List, depth)
273 g.writeIndent(s, depth)
274 s.WriteString("}")
275 case *ast.FuncType:
276 // eg. "type Handler func() any"
277
278 g.writeStartModifier(s, depth)
279 s.WriteString("interface ")
280 s.WriteString(typeName)
281
282 if ts.TypeParams != nil {
283 g.writeTypeParamsFields(s, ts.TypeParams.List)
284 }
285
286 s.WriteString(" {")
287 g.writeFuncType(s, v, depth, false)
288 g.writeIndent(s, depth)
289 s.WriteString("}")
290 default:
291 // other Go type declarations like "type JsonArray []any"
292 // (note: we don't use "type X = Y", but "interface X extends Y" syntax to allow later defining methods to the X type)
293
294 var baseType string
295 subSB := new(strings.Builder)
296 g.writeType(subSB, ts.Type, depth, optionParenthesis, optionExtends)
297 switch baseType = subSB.String(); baseType {
298 // primitives can't be extended so we use their Object equivivalents
299 case "number", "string", "boolean":
300 baseType = strings.ToUpper(string(baseType[0])) + baseType[1:]
301 case "any":
302 baseType = BaseTypeAny
303 }
304
305 g.writeStartModifier(s, depth)
306 s.WriteString("interface ")
307 s.WriteString(typeName)
308
309 if ts.TypeParams != nil {
310 g.writeTypeParamsFields(s, ts.TypeParams.List)
311 }
312
313 s.WriteString(" extends ")
314
315 s.WriteString(baseType)
316
317 s.WriteString("{}")
318 }
319
320 if ts.Comment != nil {
321 s.WriteString(" // " + ts.Comment.Text())
322 } else {
323 s.WriteString("\n")
324 }
325 }
326
327 // Writing of value specs, which are exported const expressions like
328 // const SomeValue = 3
329 func (g *PackageGenerator) writeValueSpec(s *strings.Builder, vs *ast.ValueSpec, group *groupContext, depth int) {
330 for i, name := range vs.Names {
331 group.iotaValue = group.iotaValue + 1
332 if name.Name == "_" {
333 continue
334 }
335
336 if !g.isTypeAllowed(name.Name) {
337 continue
338 } else {
339 g.markTypeAsGenerated(name.Name)
340 }
341
342 constName := name.Name
343 if isReservedIdentifier(constName) {
344 constName = "_" + constName
345 }
346
347 if vs.Doc != nil { // The spec has its own comment, which overrules the grouped comment.
348 g.writeCommentGroup(s, vs.Doc, depth)
349 } else if group.isGroupedDeclaration {
350 g.writeCommentGroup(s, group.doc, depth)
351 }
352
353 hasExplicitValue := len(vs.Values) > i
354 if hasExplicitValue {
355 group.groupType = ""
356 }
357
358 g.writeStartModifier(s, depth)
359 s.WriteString("const ")
360 s.WriteString(constName)
361
362 if vs.Type != nil {
363 s.WriteString(": ")
364
365 tempSB := &strings.Builder{}
366 g.writeType(tempSB, vs.Type, depth, optionParenthesis)
367 typeString := tempSB.String()
368
369 s.WriteString(typeString)
370 group.groupType = typeString
371 } else if group.groupType != "" && !hasExplicitValue {
372 s.WriteString(": ")
373 s.WriteString(group.groupType)
374 }
375
376 s.WriteString(" = ")
377
378 if hasExplicitValue {
379 val := vs.Values[i]
380 tempSB := &strings.Builder{}
381 g.writeType(tempSB, val, depth, optionParenthesis)
382
383 valueString := tempSB.String()
384 if isProbablyIotaType(valueString) {
385 iotaV, err := basicIotaOffsetValueParse(valueString)
386 if err != nil {
387 // fallback
388 group.groupValue = valueString
389 } else {
390 group.iotaOffset = iotaV
391 group.groupValue = "iota"
392 valueString = fmt.Sprint(group.iotaValue + group.iotaOffset)
393 }
394 } else {
395 group.groupValue = valueString
396 }
397 s.WriteString(valueString)
398 } else { // We must use the previous value or +1 in case of iota
399 valueString := group.groupValue
400 if group.groupValue == "iota" {
401 valueString = fmt.Sprint(group.iotaValue + group.iotaOffset)
402 }
403 s.WriteString(valueString)
404 }
405
406 if vs.Comment != nil {
407 s.WriteString(" // " + vs.Comment.Text())
408 } else {
409 s.WriteByte('\n')
410 }
411 }
412 }