/
parse.go
349 lines (308 loc) · 9.9 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
// Copyright (c) 2017 Opsidian Ltd.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package parser
import (
"errors"
"fmt"
"go/ast"
"path"
"reflect"
"strconv"
"strings"
"github.com/conflowio/conflow/src/conflow/annotations"
"github.com/conflowio/conflow/src/internal/utils"
"github.com/conflowio/conflow/src/schema"
schemadirectives "github.com/conflowio/conflow/src/schema/directives"
"github.com/conflowio/conflow/src/util"
)
type Field struct {
Dependency string
JSONPropertyName string
Name string
ParameterName string
Required bool
ResultTypeFrom bool
Schema schema.Schema
Variadic bool
}
func ParseField(
parseCtx *Context,
fieldName string,
astField *ast.Field,
pkg string,
fileComments ...*ast.Comment,
) (*Field, error) {
var comments []*ast.Comment
if astField.Doc != nil {
comments = append(comments, astField.Doc.List...)
}
comments = append(comments, fileComments...)
metadata, err := ParseMetadataFromComments(comments)
if err != nil {
return nil, err
}
jsonPropertyName := fieldName
if astField.Tag != nil {
tag, err := strconv.Unquote(astField.Tag.Value)
if err != nil {
return nil, errors.New("tag is invalid")
}
jsonTags := reflect.StructTag(tag).Get("json")
jsonTagParts := strings.Split(jsonTags, ",")
jsonName := strings.TrimSpace(jsonTagParts[0])
if jsonName != "" && jsonName != "-" {
jsonPropertyName = jsonName
}
}
var parameterName string
if jsonPropertyName != "" && schema.NameRegExp.MatchString(jsonPropertyName) {
parameterName = jsonPropertyName
}
if parameterName == "" && fieldName != "" {
if schema.NameRegExp.MatchString(fieldName) {
parameterName = fieldName
} else {
parameterName = utils.ToSnakeCase(fieldName)
if !schema.NameRegExp.MatchString(parameterName) {
return nil, fmt.Errorf("unable to generate a valid parameter name from field %q, please use @name to define one", fieldName)
}
}
}
for _, directive := range metadata.Directives {
if _, ok := directive.(*schemadirectives.Ignore); ok {
if _, ok := parseCtx.Parent.(*ast.StructType); !ok {
return nil, errors.New("the @ignore annotation can only be used on struct fields")
}
return nil, nil
}
}
fieldSchema, _, err := GetSchemaForType(parseCtx, astField.Type, pkg, metadata)
if err != nil {
return nil, err
}
if strings.HasPrefix(fieldSchema.GetDescription(), fieldName+" ") {
fieldSchema.(schema.MetadataAccessor).SetDescription(
strings.Replace(fieldSchema.GetDescription(), fieldName+" ", "It ", 1),
)
}
var dependencyName string
var required bool
var resultType bool
for _, directive := range metadata.Directives {
switch d := directive.(type) {
case *schemadirectives.Dependency:
if _, ok := parseCtx.Parent.(*ast.StructType); !ok {
return nil, errors.New("the @dependency annotation can only be used on struct fields")
}
if d.Name != "" {
if !util.StringSliceContains(validDependencies, d.Name) {
return nil, fmt.Errorf("%s dependency is invalid, valid values are: %s", d.Name, strings.Join(validDependencies, ", "))
}
dependencyName = d.Name
} else {
if util.StringSliceContains(validDependencies, fieldName) {
dependencyName = fieldName
} else {
return nil, errors.New("dependency can not be inferred from the field name, please set the name explicitly (@dependency \"name\"")
}
}
var actualType string
switch s := fieldSchema.(type) {
case *schema.Reference:
actualType = s.Ref
case *schema.Untyped:
actualType = "interface{}"
default:
actualType = s.TypeString()
}
if dependencyTypes[dependencyName] != actualType {
return nil, fmt.Errorf("%s dependency type can only be defined on a %s field", dependencyName, dependencyTypes[dependencyName])
}
case *schemadirectives.Required:
if _, ok := parseCtx.Parent.(*ast.StructType); !ok {
return nil, errors.New("the @required annotation can only be used on struct fields")
}
required = true
case *schemadirectives.ResultType:
if _, ok := parseCtx.Parent.(*ast.FuncType); !ok {
return nil, errors.New("the @result_type annotation can only be used on function parameters")
}
resultType = true
case *schemadirectives.Name:
parameterName = d.Value
}
}
if fieldSchema.GetAnnotation(annotations.ID) == "true" &&
fieldSchema.GetAnnotation(annotations.Value) == "true" {
return nil, errors.New("the id field can not be marked as the value field")
}
if fieldSchema.GetReadOnly() && fieldSchema.GetAnnotation(annotations.ID) != "true" {
fieldSchema.(schema.MetadataAccessor).SetAnnotation(annotations.EvalStage, "close")
}
if fieldSchema.GetAnnotation(annotations.Generated) == "true" {
fieldSchema.(schema.MetadataAccessor).SetAnnotation(annotations.EvalStage, "init")
required = true
}
var variadic bool
if _, ok := astField.Type.(*ast.Ellipsis); ok {
variadic = true
}
return &Field{
Dependency: dependencyName,
JSONPropertyName: jsonPropertyName,
Name: fieldName,
ParameterName: parameterName,
Required: required,
ResultTypeFrom: resultType,
Schema: fieldSchema,
Variadic: variadic,
}, nil
}
func GetSchemaForType(parseCtx *Context, typeNode ast.Expr, pkg string, metadata *Metadata) (schema.Schema, bool, error) {
s, isRef, err := getBaseSchemaForType(parseCtx, typeNode, pkg)
if err != nil {
return nil, false, err
}
if metadata.Description != "" {
s.(schema.MetadataAccessor).SetDescription(metadata.Description)
}
for _, directive := range metadata.Directives {
if err := directive.ApplyToSchema(s); err != nil {
return nil, false, err
}
}
return s, isRef, nil
}
func getBaseSchemaForType(parseCtx *Context, typeNode ast.Expr, pkg string) (schema.Schema, bool, error) {
switch tn := typeNode.(type) {
case *ast.Ident:
switch tn.String() {
case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "float32",
"complex64", "complex128", "int", "uint", "uintptr", "byte", "rune":
return nil, false, fmt.Errorf("type %s is not allowed", tn.String())
case "int64":
return &schema.Integer{}, false, nil
case "float64":
return &schema.Number{}, false, nil
case "bool":
return &schema.Boolean{}, false, nil
case "string":
return &schema.String{}, false, nil
default:
filePath := parseCtx.FileSet.File(parseCtx.File.Pos()).Name()
astFile, expr, metadata, err := FindType(parseCtx.WithWorkdir(path.Dir(filePath)), pkg, tn.String())
if err != nil {
return nil, false, fmt.Errorf("failed to parse %s: %w", tn.String(), err)
}
switch e := expr.(type) {
case *ast.StructType:
return &schema.Reference{
Ref: fmt.Sprintf("%s.%s", pkg, tn.String()),
}, true, nil
default:
return GetSchemaForType(parseCtx.WithFile(astFile), e, pkg, metadata)
}
}
case *ast.ArrayType:
// []byte (or []uint8) is a special case
if ident, ok := tn.Elt.(*ast.Ident); ok {
if ident.String() == "byte" || ident.String() == "uint8" {
if formatName, _, ok := schema.GetFormatForType("[]uint8"); ok {
return &schema.String{Format: formatName}, false, nil
}
}
}
itemsSchema, isRef, err := getBaseSchemaForType(parseCtx, tn.Elt, pkg)
if err != nil {
return nil, false, err
}
return &schema.Array{
Items: itemsSchema,
}, isRef, nil
case *ast.MapType:
keyIdent, ok := tn.Key.(*ast.Ident)
if !ok || keyIdent.String() != "string" {
return nil, false, fmt.Errorf("only string map keys are supported")
}
propertiesSchema, isRef, err := getBaseSchemaForType(parseCtx, tn.Value, pkg)
if err != nil {
return nil, false, err
}
return &schema.Map{
AdditionalProperties: propertiesSchema,
}, isRef, nil
case *ast.StarExpr:
res, isRef, err := getBaseSchemaForType(parseCtx, tn.X, pkg)
if err != nil {
return nil, false, err
}
nullable, ok := res.(schema.Nullable)
if !ok {
return nil, false, fmt.Errorf("%s schema type doesn't allow pointer types", res.Type())
}
nullable.SetNullable(true)
return res, isRef, nil
case *ast.SelectorExpr:
if xIdent, ok := tn.X.(*ast.Ident); ok {
path := GetImportPath(parseCtx.File, xIdent.Name)
if path == "" {
return nil, false, fmt.Errorf("could not find import path for %s", xIdent.Name)
}
switch path + "." + tn.Sel.Name {
case "github.com/conflowio/conflow/src/conflow.ID":
return &schema.String{
Format: schema.FormatConflowID,
Metadata: schema.Metadata{
ReadOnly: true,
},
}, false, nil
case "io.ReadCloser":
return &schema.ByteStream{}, false, nil
}
if formatName, _, ok := schema.GetFormatForType(path + "." + tn.Sel.Name); ok {
return &schema.String{Format: formatName}, false, nil
}
astFile, expr, metadata, err := FindType(parseCtx, path, tn.Sel.Name)
if err != nil {
return nil, false, fmt.Errorf("failed to parse %s.%s: %w", xIdent.Name, tn.Sel.Name, err)
}
switch e := expr.(type) {
case *ast.StructType:
return &schema.Reference{
Ref: fmt.Sprintf("%s.%s", path, tn.Sel.Name),
}, true, nil
default:
return GetSchemaForType(parseCtx.WithFile(astFile), e, path, metadata)
}
}
return nil, false, fmt.Errorf("unexpected ast node: %T: %v", typeNode, typeNode)
case *ast.InterfaceType:
return &schema.Untyped{}, false, nil
case *ast.Ellipsis:
return getBaseSchemaForType(parseCtx, tn.Elt, pkg)
default:
return nil, false, fmt.Errorf("unexpected ast node: %T: %v", typeNode, typeNode)
}
}
func GetImportPath(file *ast.File, name string) string {
if name == "time" || name == "io" {
return name
}
for _, i := range file.Imports {
path, _ := strconv.Unquote(i.Path.Value)
if i.Name != nil {
if i.Name.Name == name {
return path
}
} else {
parts := strings.Split(path, "/")
if parts[len(parts)-1] == name {
return path
}
}
}
return ""
}