-
Notifications
You must be signed in to change notification settings - Fork 793
/
parse.go
369 lines (344 loc) · 10.2 KB
/
parse.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/*
* Copyright 2021 CloudWeGo 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.
*/
package thrift
import (
"errors"
"fmt"
"github.com/cloudwego/kitex/pkg/generic/descriptor"
"github.com/cloudwego/thriftgo/parser"
"github.com/cloudwego/thriftgo/semantic"
)
const (
initRecursionDepth = 0
)
// ParseMode .
type ParseMode int
const (
// LastServiceOnly forces the parser to parse only the last service definition.
LastServiceOnly ParseMode = iota
// FirstServiceOnly forces the parser to parse only the first service definition.
FirstServiceOnly
// CombineServices forces the parser to combine methods of all service definitions.
// Note that method names of the service definitions can not be duplicate.
CombineServices
)
var defaultParseMode = LastServiceOnly
// DefaultParseMode returns the default parse mode.
func DefaultParseMode() ParseMode {
return defaultParseMode
}
// SetDefaultParseMode sets the default parse mode.
func SetDefaultParseMode(m ParseMode) {
defaultParseMode = m
}
// Parse descriptor from parser.Thrift
func Parse(tree *parser.Thrift, mode ParseMode) (*descriptor.ServiceDescriptor, error) {
if len(tree.Services) == 0 {
return nil, errors.New("empty serverce from idls")
}
if err := semantic.ResolveSymbols(tree); err != nil {
return nil, err
}
sDsc := &descriptor.ServiceDescriptor{
Functions: map[string]*descriptor.FunctionDescriptor{},
Router: descriptor.NewRouter(),
}
structsCache := map[string]*descriptor.TypeDescriptor{}
// support one service
svcs := tree.Services
switch mode {
case LastServiceOnly:
svcs = svcs[len(svcs)-1:]
sDsc.Name = svcs[len(svcs)-1].Name
case FirstServiceOnly:
svcs = svcs[:1]
sDsc.Name = svcs[0].Name
case CombineServices:
sDsc.Name = "CombinedServices"
}
visitedSvcs := make(map[*parser.Service]bool, len(tree.Services))
for _, svc := range svcs {
for p := range getAllFunctions(svc, tree, visitedSvcs) {
fn := p.data.(*parser.Function)
if err := addFunction(fn, p.tree, sDsc, structsCache); err != nil {
return nil, err
}
}
}
return sDsc, nil
}
type pair struct {
tree *parser.Thrift
data interface{}
}
func getAllFunctions(svc *parser.Service, tree *parser.Thrift, visitedSvcs map[*parser.Service]bool) chan *pair {
ch := make(chan *pair)
svcs := make(chan *pair)
addSvc := func(tree *parser.Thrift, svc *parser.Service) {
if exist := visitedSvcs[svc]; !exist {
svcs <- &pair{tree: tree, data: svc}
visitedSvcs[svc] = true
}
}
go func() {
addSvc(tree, svc)
for base := svc.Extends; base != ""; base = svc.Extends {
ref := svc.GetReference()
if ref != nil {
idx := ref.GetIndex()
base = ref.GetName()
tree = tree.Includes[idx].Reference
}
svc, _ = tree.GetService(base)
addSvc(tree, svc)
}
close(svcs)
}()
go func() {
for p := range svcs {
svc := p.data.(*parser.Service)
for _, fn := range svc.Functions {
ch <- &pair{
tree: p.tree,
data: fn,
}
}
}
close(ch)
}()
return ch
}
func addFunction(fn *parser.Function, tree *parser.Thrift, sDsc *descriptor.ServiceDescriptor, structsCache map[string]*descriptor.TypeDescriptor) error {
if sDsc.Functions[fn.Name] != nil {
return fmt.Errorf("duplicate method name: %s", fn.Name)
}
if len(fn.Arguments) == 0 {
return fmt.Errorf("empty arguments in function: %s", fn.Name)
}
// only support single argument
field := fn.Arguments[0]
req := &descriptor.TypeDescriptor{
Type: descriptor.STRUCT,
Struct: &descriptor.StructDescriptor{
FieldsByID: map[int32]*descriptor.FieldDescriptor{},
FieldsByName: map[string]*descriptor.FieldDescriptor{},
},
}
reqType, err := parseType(field.Type, tree, structsCache, initRecursionDepth)
if err != nil {
return err
}
hasRequestBase := false
if reqType.Type == descriptor.STRUCT {
for _, f := range reqType.Struct.FieldsByName {
if f.Type.IsRequestBase {
hasRequestBase = true
break
}
}
}
reqField := &descriptor.FieldDescriptor{
Name: field.Name,
ID: field.ID,
Type: reqType,
}
req.Struct.FieldsByID[field.ID] = reqField
req.Struct.FieldsByName[field.Name] = reqField
// parse response filed
resp := &descriptor.TypeDescriptor{
Type: descriptor.STRUCT,
Struct: &descriptor.StructDescriptor{
FieldsByID: map[int32]*descriptor.FieldDescriptor{},
FieldsByName: map[string]*descriptor.FieldDescriptor{},
},
}
respType, err := parseType(fn.FunctionType, tree, structsCache, initRecursionDepth)
if err != nil {
return err
}
respField := &descriptor.FieldDescriptor{
Type: respType,
}
// response has no name or id
resp.Struct.FieldsByID[0] = respField
resp.Struct.FieldsByName[""] = respField
if len(fn.Throws) > 0 {
// only support single exception
field := fn.Throws[0]
exceptionType, err := parseType(field.Type, tree, structsCache, initRecursionDepth)
if err != nil {
return err
}
exceptionField := &descriptor.FieldDescriptor{
Name: field.Name,
ID: field.ID,
IsException: true,
Type: exceptionType,
}
resp.Struct.FieldsByID[field.ID] = exceptionField
resp.Struct.FieldsByName[field.Name] = exceptionField
}
fnDsc := &descriptor.FunctionDescriptor{
Name: fn.Name,
Oneway: fn.Oneway,
Request: req,
Response: resp,
HasRequestBase: hasRequestBase,
}
for _, ann := range fn.Annotations {
for _, v := range ann.GetValues() {
if handle, ok := descriptor.FindAnnotation(ann.GetKey(), v); ok {
if nr, ok := handle.(descriptor.NewRoute); ok {
sDsc.Router.Handle(nr(v, fnDsc))
break
}
}
}
}
sDsc.Functions[fn.Name] = fnDsc
return nil
}
// reuse builtin types
var builtinTypes = map[string]*descriptor.TypeDescriptor{
"void": {Name: "void", Type: descriptor.VOID, Struct: new(descriptor.StructDescriptor)},
"bool": {Name: "bool", Type: descriptor.BOOL},
"byte": {Name: "byte", Type: descriptor.BYTE},
"i8": {Name: "i8", Type: descriptor.I08},
"i16": {Name: "i16", Type: descriptor.I16},
"i32": {Name: "i32", Type: descriptor.I32},
"i64": {Name: "i64", Type: descriptor.I64},
"double": {Name: "double", Type: descriptor.DOUBLE},
"string": {Name: "string", Type: descriptor.STRING},
"binary": {Name: "binary", Type: descriptor.STRING},
}
// arg cache:
// only support self reference on the same file
// cross file self reference complicate matters
func parseType(t *parser.Type, tree *parser.Thrift, cache map[string]*descriptor.TypeDescriptor, recursionDepth int) (*descriptor.TypeDescriptor, error) {
if ty, ok := builtinTypes[t.Name]; ok {
return ty, nil
}
nextRecursionDepth := recursionDepth + 1
var err error
switch t.Name {
case "list":
ty := &descriptor.TypeDescriptor{Name: t.Name}
ty.Type = descriptor.LIST
ty.Elem, err = parseType(t.ValueType, tree, cache, nextRecursionDepth)
return ty, err
case "set":
ty := &descriptor.TypeDescriptor{Name: t.Name}
ty.Type = descriptor.SET
ty.Elem, err = parseType(t.ValueType, tree, cache, nextRecursionDepth)
return ty, err
case "map":
ty := &descriptor.TypeDescriptor{Name: t.Name}
ty.Type = descriptor.MAP
if ty.Key, err = parseType(t.KeyType, tree, cache, nextRecursionDepth); err != nil {
return nil, err
}
ty.Elem, err = parseType(t.ValueType, tree, cache, nextRecursionDepth)
return ty, err
default:
// check the cache
if ty, ok := cache[t.Name]; ok {
return ty, nil
}
typePkg, typeName := splitType(t.Name)
if typePkg != "" {
ref, ok := tree.GetReference(typePkg)
if !ok {
return nil, fmt.Errorf("miss reference: %s", typePkg)
}
tree = ref
// cross file reference need empty cache
cache = map[string]*descriptor.TypeDescriptor{}
}
if typDef, ok := tree.GetTypedef(typeName); ok {
return parseType(typDef.Type, tree, cache, nextRecursionDepth)
}
if _, ok := tree.GetEnum(typeName); ok {
return builtinTypes["i32"], nil
}
var st *parser.StructLike
var ok bool
st, ok = tree.GetUnion(typeName)
if !ok {
st, ok = tree.GetStruct(typeName)
}
if !ok {
st, ok = tree.GetException(typeName)
}
if !ok {
return nil, fmt.Errorf("missing type: %s", typeName)
}
ty := &descriptor.TypeDescriptor{
Name: t.Name,
Type: descriptor.STRUCT,
Struct: &descriptor.StructDescriptor{
Name: typeName,
FieldsByID: map[int32]*descriptor.FieldDescriptor{},
FieldsByName: map[string]*descriptor.FieldDescriptor{},
RequiredFields: map[int32]*descriptor.FieldDescriptor{},
},
// the first depth of base.Base is Request Base
IsRequestBase: t.Name == "base.Base" && recursionDepth == 1,
}
// cannot cache the request base
if !ty.IsRequestBase {
cache[t.Name] = ty
}
for _, field := range st.Fields {
_f := &descriptor.FieldDescriptor{
ID: field.ID,
Name: field.Name,
Required: field.Requiredness == parser.FieldType_Required,
}
for _, ann := range field.Annotations {
for _, v := range ann.GetValues() {
if handle, ok := descriptor.FindAnnotation(ann.GetKey(), v); ok {
switch h := handle.(type) {
case descriptor.NewHTTPMapping:
_f.HTTPMapping = h(v)
case descriptor.NewValueMapping:
_f.ValueMapping = h(v)
case descriptor.NewFieldMapping:
// execute at compile time
h(v).Handle(_f)
case nil:
// none annotation
default:
// not supported annotation type
return nil, fmt.Errorf("not supported handle type: %T", handle)
}
}
}
}
if _f.HTTPMapping == nil {
_f.HTTPMapping = descriptor.DefaultNewMapping(_f.FieldName())
}
if _f.Type, err = parseType(field.Type, tree, cache, nextRecursionDepth); err != nil {
return nil, err
}
ty.Struct.FieldsByID[field.ID] = _f
ty.Struct.FieldsByName[_f.FieldName()] = _f
if _f.Required {
ty.Struct.RequiredFields[field.ID] = _f
}
}
return ty, nil
}
}