Debian Codegraph @

cli/xgotext/parser/golang.go

raw
1 package parser
2
3 import (
4 "fmt"
5 "go/ast"
6 "go/token"
7 "go/types"
8 "log"
9 "path/filepath"
10 "strconv"
11
12 "golang.org/x/tools/go/packages"
13 )
14
15 // GetterDef describes a getter
16 type GetterDef struct {
17 Id int
18 Plural int
19 Context int
20 Domain int
21 }
22
23 // maxArgIndex returns the largest argument index
24 func (d *GetterDef) maxArgIndex() int {
25 m := d.Id
26 if d.Plural > m {
27 m = d.Plural
28 }
29 if d.Context > m {
30 m = d.Context
31 }
32 if d.Domain > m {
33 m = d.Domain
34 }
35 return m
36 }
37
38 // list of supported getter
39 var gotextGetter = map[string]GetterDef{
40 "Get": {0, -1, -1, -1},
41 "GetN": {0, 1, -1, -1},
42 "GetD": {1, -1, -1, 0},
43 "GetND": {1, 2, -1, 0},
44 "GetC": {0, -1, 1, -1},
45 "GetNC": {0, 1, 3, -1},
46 "GetDC": {1, -1, 2, 0},
47 "GetNDC": {1, 2, 4, 0},
48 }
49
50 // register go parser
51 func init() {
52 AddParser(goParser)
53 }
54
55 // parse go package
56 func goParser(dirPath, basePath string, data *DomainMap) error {
57 fileSet := token.NewFileSet()
58
59 conf := packages.Config{
60 Mode: packages.NeedName |
61 packages.NeedFiles |
62 packages.NeedSyntax |
63 packages.NeedTypes |
64 packages.NeedTypesInfo,
65 Fset: fileSet,
66 Dir: basePath,
67 }
68
69 // load package from path
70 pkgs, err := packages.Load(&packages.Config{
71 Mode: conf.Mode,
72 Fset: fileSet,
73 Dir: dirPath,
74 })
75 if err != nil || len(pkgs) == 0 {
76 // not a go package
77 return nil
78 }
79
80 // handle each file
81 for _, node := range pkgs[0].Syntax {
82 file := GoFile{
83 pkgConf: &conf,
84 filePath: fileSet.Position(node.Package).Filename,
85 basePath: basePath,
86 data: data,
87 fileSet: fileSet,
88
89 importedPackages: map[string]*packages.Package{
90 pkgs[0].Name: pkgs[0],
91 },
92 }
93
94 ast.Inspect(node, file.inspectFile)
95 }
96 return nil
97 }
98
99 // GoFile handles the parsing of one go file
100 type GoFile struct {
101 filePath string
102 basePath string
103 data *DomainMap
104
105 fileSet *token.FileSet
106 pkgConf *packages.Config
107
108 importedPackages map[string]*packages.Package
109 }
110
111 // getPackage loads module by name
112 func (g *GoFile) getPackage(name string) (*packages.Package, error) {
113 pkgs, err := packages.Load(g.pkgConf, name)
114 if err != nil {
115 return nil, err
116 }
117 if len(pkgs) == 0 {
118 return nil, nil
119 }
120 return pkgs[0], nil
121 }
122
123 // getType from ident object
124 func (g *GoFile) getType(ident *ast.Ident) types.Object {
125 for _, pkg := range g.importedPackages {
126 if obj, ok := pkg.TypesInfo.Uses[ident]; ok {
127 return obj
128 }
129 }
130 return nil
131 }
132
133 func (g *GoFile) inspectFile(n ast.Node) bool {
134 switch x := n.(type) {
135 // get names of imported packages
136 case *ast.ImportSpec:
137 packageName, _ := strconv.Unquote(x.Path.Value)
138
139 pkg, err := g.getPackage(packageName)
140 if err != nil {
141 log.Printf("failed to load package %s: %s", packageName, err)
142 } else {
143 if x.Name == nil {
144 g.importedPackages[pkg.Name] = pkg
145 } else {
146 g.importedPackages[x.Name.Name] = pkg
147 }
148 }
149
150 // check each function call
151 case *ast.CallExpr:
152 g.inspectCallExpr(x)
153
154 default:
155 print()
156 }
157
158 return true
159 }
160
161 // checkType for gotext object
162 func (g *GoFile) checkType(rawType types.Type) bool {
163 switch t := rawType.(type) {
164 case *types.Pointer:
165 return g.checkType(t.Elem())
166
167 case *types.Named:
168 if t.Obj().Pkg() == nil || t.Obj().Pkg().Path() != "github.com/leonelquinteros/gotext" {
169 return false
170 }
171 default:
172 return false
173 }
174 return true
175 }
176
177 func (g *GoFile) inspectCallExpr(n *ast.CallExpr) {
178 // must be a selector expression otherwise it is a local function call
179 expr, ok := n.Fun.(*ast.SelectorExpr)
180 if !ok {
181 return
182 }
183
184 switch e := expr.X.(type) {
185 // direct call
186 case *ast.Ident:
187 // object is a package if the Obj is not set
188 if e.Obj == nil {
189 pkg, ok := g.importedPackages[e.Name]
190 if !ok || pkg.PkgPath != "github.com/leonelquinteros/gotext" {
191 return
192 }
193
194 } else {
195 // validate type of object
196 t := g.getType(e)
197 if t == nil || !g.checkType(t.Type()) {
198 return
199 }
200 }
201
202 // call to attribute
203 case *ast.SelectorExpr:
204 // validate type of object
205 t := g.getType(e.Sel)
206 if t == nil || !g.checkType(t.Type()) {
207 return
208 }
209
210 default:
211 return
212 }
213
214 // convert args
215 args := make([]*ast.BasicLit, len(n.Args))
216 for idx, arg := range n.Args {
217 args[idx], _ = arg.(*ast.BasicLit)
218 }
219
220 // get position
221 path, _ := filepath.Rel(g.basePath, g.filePath)
222 position := fmt.Sprintf("%s:%d", path, g.fileSet.Position(n.Lparen).Line)
223
224 // handle getters
225 if def, ok := gotextGetter[expr.Sel.String()]; ok {
226 g.parseGetter(def, args, position)
227 return
228 }
229 }
230
231 func (g *GoFile) parseGetter(def GetterDef, args []*ast.BasicLit, pos string) {
232 // check if enough arguments are given
233 if len(args) < def.maxArgIndex() {
234 return
235 }
236
237 // get domain
238 var domain string
239 if def.Domain != -1 {
240 domain, _ = strconv.Unquote(args[def.Domain].Value)
241 }
242
243 // only handle function calls with strings as ID
244 if args[def.Id] == nil || args[def.Id].Kind != token.STRING {
245 log.Printf("ERR: Unsupported call at %s (ID not a string)", pos)
246 return
247 }
248
249 trans := Translation{
250 MsgId: args[def.Id].Value,
251 SourceLocations: []string{pos},
252 }
253 if def.Plural > 0 {
254 // plural ID must be a string
255 if args[def.Plural] == nil || args[def.Plural].Kind != token.STRING {
256 log.Printf("ERR: Unsupported call at %s (Plural not a string)", pos)
257 return
258 }
259 trans.MsgIdPlural = args[def.Plural].Value
260 }
261 if def.Context > 0 {
262 // Context must be a string
263 if args[def.Context] == nil || args[def.Context].Kind != token.STRING {
264 log.Printf("ERR: Unsupported call at %s (Context not a string)", pos)
265 return
266 }
267 trans.Context = args[def.Context].Value
268 }
269
270 g.data.AddTranslation(domain, &trans)
271 }