Debian Codegraph @

package_generator.go

raw symbols SCIP
1 package tygoja
2
3 import (
4 "go/ast"
5 "go/token"
6 "strings"
7
8 "golang.org/x/tools/go/packages"
9 )
10
11 // PackageGenerator is responsible for generating the code for a single input package.
12 type PackageGenerator struct {
13 conf *Config
14 pkg *packages.Package
15 types []string
16 withPkgDoc bool
17
18 generatedTypes map[string]struct{}
19 unknownTypes map[string]struct{}
20 imports map[string][]string // path -> []names/aliases
21 }
22
23 // Generate generates the typings for a single package.
24 func (g *PackageGenerator) Generate() (string, error) {
25 s := new(strings.Builder)
26
27 namespace := packageNameFromPath(g.pkg.ID)
28
29 s.WriteString("\n")
30
31 if g.withPkgDoc {
32 for _, f := range g.pkg.Syntax {
33 if f.Doc == nil || len(f.Doc.List) == 0 {
34 continue
35 }
36 g.writeCommentGroup(s, f.Doc, 0)
37 }
38 }
39
40 g.writeStartModifier(s, 0)
41 s.WriteString("namespace ")
42 s.WriteString(namespace)
43 s.WriteString(" {\n")
44
45 // register the aliased imports within the package namespace
46 // (see https://www.typescriptlang.org/docs/handbook/namespaces.html#aliases)
47 loadedAliases := map[string]struct{}{}
48 for _, file := range g.pkg.Syntax {
49 for _, imp := range file.Imports {
50 path := strings.Trim(imp.Path.Value, `"' `)
51
52 pgkName := packageNameFromPath(path)
53 alias := pgkName
54
55 if imp.Name != nil && imp.Name.Name != "" && imp.Name.Name != "_" {
56 alias = imp.Name.Name
57
58 if _, ok := loadedAliases[alias]; ok {
59 continue // already registered
60 }
61
62 loadedAliases[alias] = struct{}{}
63
64 g.writeIndent(s, 1)
65 s.WriteString("// @ts-ignore\n")
66 g.writeIndent(s, 1)
67 s.WriteString("import ")
68 s.WriteString(alias)
69 s.WriteString(" = ")
70 s.WriteString(pgkName)
71 s.WriteString("\n")
72 }
73
74 // register the import to export its package later
75 if !exists(g.imports[path], alias) {
76 if g.imports[path] == nil {
77 g.imports[path] = []string{}
78 }
79 g.imports[path] = append(g.imports[path], alias)
80 }
81 }
82
83 ast.Inspect(file, func(n ast.Node) bool {
84 switch x := n.(type) {
85 case *ast.FuncDecl: // FuncDecl can be package level function or struct method
86 g.writeFuncDecl(s, x, 1)
87 return false
88 case *ast.GenDecl: // GenDecl can be an import, type, var, or const expression
89 if x.Tok == token.VAR || x.Tok == token.IMPORT {
90 return false // ignore variables and import statements for now
91 }
92
93 g.writeGroupDecl(s, x, 1)
94 return false
95 }
96
97 return true
98 })
99 }
100
101 s.WriteString("}\n")
102
103 return s.String(), nil
104 }