/
transform.go
256 lines (222 loc) · 6.35 KB
/
transform.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
// Copyright 2016 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This file implements .go code transformation.
package main
import (
"bytes"
"fmt"
"io/ioutil"
"strings"
"text/template"
"unicode/utf8"
"go/ast"
"go/format"
"go/parser"
"go/printer"
"go/token"
)
const (
prpcPackagePath = `go.chromium.org/luci/grpc/prpc`
)
var (
serverPrpcPkg = ast.NewIdent("prpc")
)
type transformer struct {
fset *token.FileSet
inPRPCPackage bool
services []*service
PackageName string
}
// transformGoFile rewrites a .go file to work with prpc.
func (t *transformer) transformGoFile(filename string) error {
t.fset = token.NewFileSet()
file, err := parser.ParseFile(t.fset, filename, nil, parser.ParseComments)
if err != nil {
return err
}
t.PackageName = file.Name.Name
t.services, err = getServices(file)
if err != nil {
return err
}
if len(t.services) == 0 {
return nil
}
t.inPRPCPackage, err = isInPackage(filename, prpcPackagePath)
if err != nil {
return err
}
if err := t.transformFile(file); err != nil {
return err
}
var buf bytes.Buffer
if err := printer.Fprint(&buf, t.fset, file); err != nil {
return err
}
formatted, err := gofmt(buf.Bytes())
if err != nil {
return err
}
return ioutil.WriteFile(filename, formatted, 0666)
}
func (t *transformer) transformFile(file *ast.File) error {
var includePrpc bool
for _, s := range t.services {
if err := s.complete(); err != nil {
return fmt.Errorf("incomplete service %q: %s", s.name, err)
}
t.transformRegisterServerFuncs(s)
if !t.inPRPCPackage {
includePrpc = true
}
if err := t.generateClients(file, s); err != nil {
return err
}
}
if includePrpc {
t.insertImport(file, serverPrpcPkg, prpcPackagePath)
}
return nil
}
// transformRegisterServerFuncs finds RegisterXXXServer functions and
// checks its first parameter type to prpc.Registrar.
// Returns true if modified ast.
func (t *transformer) transformRegisterServerFuncs(s *service) {
registrarName := ast.NewIdent("Registrar")
var registrarType ast.Expr = registrarName
if !t.inPRPCPackage {
registrarType = &ast.SelectorExpr{serverPrpcPkg, registrarName}
}
s.registerServerFunc.Params.List[0].Type = registrarType
}
// generateClients finds client interface declarations
// and inserts pRPC implementations after them.
func (t *transformer) generateClients(file *ast.File, s *service) error {
switch newDecls, err := t.generateClient(s.protoPackageName, s.name, s.clientIface); {
case err != nil:
return err
case len(newDecls) > 0:
insertAST(file, s.clientIfaceDecl, newDecls)
return nil
default:
return nil
}
}
func insertAST(file *ast.File, after ast.Decl, newDecls []ast.Decl) {
for i, d := range file.Decls {
if d == after {
file.Decls = append(file.Decls[:i+1], append(newDecls, file.Decls[i+1:]...)...)
return
}
}
panic("unable to find after node")
}
var clientCodeTemplate = template.Must(template.New("").Parse(`
package template
type {{$.StructName}} struct {
client *{{.PRPCSymbolPrefix}}Client
}
func New{{.Service}}PRPCClient(client *{{.PRPCSymbolPrefix}}Client) {{.Service}}Client {
return &{{$.StructName}}{client}
}
{{range .Methods}}
func (c *{{$.StructName}}) {{.Name}}(ctx context.Context, in *{{.InputMessage}}, opts ...grpc.CallOption) (*{{.OutputMessage}}, error) {
out := new({{.OutputMessage}})
err := c.client.Call(ctx, "{{$.ProtoPkg}}.{{$.Service}}", "{{.Name}}", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
{{end}}
`))
// generateClient generates pRPC implementation of a client interface.
func (t *transformer) generateClient(protoPackage, serviceName string, iface *ast.InterfaceType) ([]ast.Decl, error) {
// This function used to construct an AST. It was a lot of code.
// Now it generates code via a template and parses back to AST.
// Slower, but saner and easier to make changes.
type Method struct {
Name string
InputMessage string
OutputMessage string
}
methods := make([]Method, 0, len(iface.Methods.List))
var buf bytes.Buffer
toGoCode := func(n ast.Node) (string, error) {
defer buf.Reset()
err := format.Node(&buf, t.fset, n)
if err != nil {
return "", err
}
return buf.String(), nil
}
for _, m := range iface.Methods.List {
signature, ok := m.Type.(*ast.FuncType)
if !ok {
return nil, fmt.Errorf("unexpected embedded interface in %sClient", serviceName)
}
inStructPtr := signature.Params.List[1].Type.(*ast.StarExpr)
inStruct, err := toGoCode(inStructPtr.X)
if err != nil {
return nil, err
}
outStructPtr := signature.Results.List[0].Type.(*ast.StarExpr)
outStruct, err := toGoCode(outStructPtr.X)
if err != nil {
return nil, err
}
methods = append(methods, Method{
Name: m.Names[0].Name,
InputMessage: inStruct,
OutputMessage: outStruct,
})
}
prpcSymbolPrefix := "prpc."
if t.inPRPCPackage {
prpcSymbolPrefix = ""
}
err := clientCodeTemplate.Execute(&buf, map[string]interface{}{
"Service": serviceName,
"ProtoPkg": protoPackage,
"StructName": firstLower(serviceName) + "PRPCClient",
"Methods": methods,
"PRPCSymbolPrefix": prpcSymbolPrefix,
})
if err != nil {
return nil, fmt.Errorf("client template execution: %s", err)
}
f, err := parser.ParseFile(t.fset, "", buf.String(), 0)
if err != nil {
return nil, fmt.Errorf("client template result parsing: %s. Code: %#v", err, buf.String())
}
return f.Decls, nil
}
func (t *transformer) insertImport(file *ast.File, name *ast.Ident, path string) {
spec := &ast.ImportSpec{
Name: name,
Path: &ast.BasicLit{
Kind: token.STRING,
Value: `"` + path + `"`,
},
}
importDecl := &ast.GenDecl{
Tok: token.IMPORT,
Specs: []ast.Spec{spec},
}
file.Decls = append([]ast.Decl{importDecl}, file.Decls...)
}
func firstLower(s string) string {
_, w := utf8.DecodeRuneInString(s)
return strings.ToLower(s[:w]) + s[w:]
}