-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcodegen_go.go
481 lines (364 loc) · 12.8 KB
/
codegen_go.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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
package presilo
import (
"bytes"
"regexp"
"strings"
)
/*
Generates valid Go code for a given schema.
*/
func GenerateGo(schema *ObjectSchema, module string, tabstyle string) string {
var buffer *BufferedFormatString
buffer = NewBufferedFormatString(tabstyle)
buffer.Printf("package %s", module)
buffer.Print("\n")
generateGoImports(schema, buffer)
buffer.Print("\n")
generateGoTypeDeclaration(schema, buffer)
buffer.Print("\n")
generateGoConstructor(schema, buffer)
buffer.Print("\n")
generateGoFunctions(schema, buffer)
buffer.Print("\n")
return buffer.String()
}
func ValidateGoModule(module string) bool {
matched, err := regexp.MatchString("^[a-zA-Z_]+[0-9a-zA-Z_]*$", module)
return err == nil && matched
}
func generateGoImports(schema *ObjectSchema, buffer *BufferedFormatString) {
var imports []string
// import errors if there are any constrained fields
if len(schema.ConstrainedProperties) > 0 {
imports = append(imports, "errors")
}
// if any string schema has a pattern match, import regex.
if containsRegexpMatch(schema) {
imports = append(imports, "regexp")
}
// if any number (but not integer!) has a multiple clause, import math
if containsNumberMod(schema) {
imports = append(imports, "math")
}
// write imports (if they exist)
if len(imports) > 0 {
buffer.Print("import (\n")
for _, packageName := range imports {
buffer.Printf("\"%s\"\n", packageName)
}
buffer.Print(")\n")
}
}
/*
Generates the type declaration for this schema,
including all member fields (properly exported if they have no constraints),
and struct tags.
Also includes the doc comments.
*/
func generateGoTypeDeclaration(schema *ObjectSchema, buffer *BufferedFormatString) {
var subschema TypeSchema
var propertyName string
// description first
buffer.Printf("/*\n%s\n*/\n", schema.GetDescription())
buffer.Printf("type %s struct {", schema.GetTitle())
buffer.AddIndentation(1)
// write all required fields as unexported fields.
for _, propertyName = range schema.GetOrderedPropertyNames() {
subschema = schema.Properties[propertyName]
generateVariableDeclaration(subschema, buffer, propertyName, ToStrictCamelCase)
}
buffer.AddIndentation(-1)
buffer.Print("\n}\n")
}
/*
Generates getters and setters for all fields in the given schema
which have constraints.
fields without constraints are assumed to be exported.
*/
func generateGoFunctions(schema *ObjectSchema, buffer *BufferedFormatString) {
var subschema TypeSchema
var propertyName string
for _, propertyName = range schema.ConstrainedProperties {
subschema = schema.Properties[propertyName]
propertyName = ToStrictCamelCase(propertyName)
// getter
buffer.Printf("\nfunc (this *%s) Get%s() (%s) {", schema.GetTitle(), propertyName, GenerateGoTypeForSchema(subschema))
buffer.AddIndentation(1)
buffer.Printf("\nreturn this.%s", propertyName)
buffer.AddIndentation(-1)
buffer.Print("\n}\n")
// setter
buffer.Printf("func (this *%s) Set%s(value %s) (error) {", schema.GetTitle(), propertyName, GenerateGoTypeForSchema(subschema))
buffer.AddIndentation(1)
switch subschema.GetSchemaType() {
case SCHEMATYPE_STRING:
generateGoStringSetter(subschema.(*StringSchema), buffer)
case SCHEMATYPE_NUMBER:
generateGoNumericSetter(subschema.(*NumberSchema), buffer)
case SCHEMATYPE_INTEGER:
generateGoNumericSetter(subschema.(*IntegerSchema), buffer)
case SCHEMATYPE_ARRAY:
generateGoArraySetter(subschema.(*ArraySchema), buffer)
}
buffer.Printf("\nthis.%s = value\nreturn nil", propertyName)
buffer.AddIndentation(-1)
buffer.Print("\n}\n")
}
}
/*
Generates a convenience "New*" method for the given schema,
which accepts parameters that match the 'required' properties.
Any properties which are both 'required' and have constraints
will have their setters used, instead of setting the field directly.
*/
func generateGoConstructor(schema *ObjectSchema, buffer *BufferedFormatString) {
var subschema TypeSchema
var ret bytes.Buffer
var parameters, parameterNames []string
var title string
for _, propertyName := range schema.RequiredProperties {
subschema = schema.Properties[propertyName]
parameterNames = append(parameterNames, propertyName)
propertyName = getAppropriateGoCase(schema, propertyName)
ret.WriteString(propertyName)
ret.WriteString(" ")
ret.WriteString(GenerateGoTypeForSchema(subschema))
parameters = append(parameters, ret.String())
ret.Reset()
}
// signature
title = ToCamelCase(schema.Title)
buffer.Printf("\nfunc New%s(%s)(*%s, error) {\n", title, strings.Join(parameters, ","), title)
buffer.AddIndentation(1)
buffer.Printf("\nvar err error = nil")
// body
buffer.Printf("\nret := new(%s)\n", title)
for _, propertyName := range parameterNames {
subschema = schema.Properties[propertyName]
propertyName = getAppropriateGoCase(schema, propertyName)
if subschema.HasConstraints() {
buffer.Printf("\nerr = ret.Set%s(%s)", ToStrictCamelCase(propertyName), propertyName)
buffer.Printf("\nif(err != nil) {")
buffer.AddIndentation(1)
buffer.Printf("\nreturn nil, err")
buffer.AddIndentation(-1)
buffer.Printf("\n}")
} else {
buffer.Printf("\nret.%s = %s", propertyName, propertyName)
}
}
buffer.Print("\nreturn ret, err")
buffer.AddIndentation(-1)
buffer.Print("\n}\n")
}
/*
Generates a 'setter' method for the given numeric schema.
Numeric schemas could either be NumberSchema or IntegerSchema,
since they share the same constraint set, this works on either.
*/
func generateGoNumericSetter(schema NumericSchemaType, buffer *BufferedFormatString) {
var minimum, maximum, multiple interface{}
var formatString string
var comparator string
if !schema.HasConstraints() {
return
}
formatString = schema.GetConstraintFormat()
if schema.HasEnum() {
generateGoEnumForSchema(schema, buffer, schema.GetEnum(), "", "")
}
if schema.HasMinimum() {
if schema.IsExclusiveMinimum() {
comparator = "<="
} else {
comparator = "<"
}
minimum = schema.GetMinimum()
buffer.Printf("\nif(value %s "+formatString+") {", comparator, minimum)
buffer.AddIndentation(1)
buffer.Printf("\nreturn errors.New(\"Minimum value of '"+formatString+"' not met\")", minimum)
buffer.AddIndentation(-1)
buffer.Print("\n}\n")
}
if schema.HasMaximum() {
if schema.IsExclusiveMaximum() {
comparator = ">="
} else {
comparator = ">"
}
maximum = schema.GetMaximum()
buffer.Printf("\nif(value %s "+formatString+") {", comparator, maximum)
buffer.AddIndentation(1)
buffer.Printf("\nreturn errors.New(\"Maximum value of '"+formatString+"' not met\")", maximum)
buffer.AddIndentation(-1)
buffer.Print("\n}\n")
}
if schema.HasMultiple() {
multiple = schema.GetMultiple()
if schema.GetSchemaType() == SCHEMATYPE_NUMBER {
buffer.Printf("\nif(math.Mod(value, %f) != 0) {", multiple)
} else {
buffer.Printf("\nif(value %% %d != 0) {", multiple)
}
buffer.AddIndentation(1)
buffer.Printf("\nreturn errors.New(\"Value is not a multiple of '"+formatString+"'\")", multiple)
buffer.AddIndentation(-1)
buffer.Print("\n}\n")
}
}
/*
Generates a 'setter' function for the given string schema.
Generates code which validates all schema constraints before setting.
*/
func generateGoStringSetter(schema *StringSchema, buffer *BufferedFormatString) {
var cutoff int
if schema.Enum != nil {
generateGoEnumForSchema(schema, buffer, schema.GetEnum(), "\"", "\"")
}
if schema.MinLength != nil {
cutoff = *schema.MinLength
buffer.Printf("\nif(len(value) < %d) {", cutoff)
buffer.AddIndentation(1)
buffer.Printf("\nreturn errors.New(\"Value is shorter than minimum length of %d\")", cutoff)
buffer.AddIndentation(-1)
buffer.Printf("\n}\n")
}
if schema.MaxLength != nil {
cutoff = *schema.MaxLength
buffer.Printf("\nif(len(value) > %d) {", cutoff)
buffer.AddIndentation(1)
buffer.Printf("\nreturn errors.New(\"Value is greater than maximum length of %d\")", cutoff)
buffer.AddIndentation(-1)
buffer.Printf("\n}\n")
}
if schema.MaxByteLength != nil {
cutoff = *schema.MaxByteLength
buffer.Printf("\nif(len([]byte(value)) > %d) {", cutoff)
buffer.AddIndentation(1)
buffer.Printf("\nreturn errors.New(\"Value's byte length is longer than maximum length of %d\")", cutoff)
buffer.AddIndentation(-1)
buffer.Printf("\n}\n")
}
if schema.MinByteLength != nil {
cutoff = *schema.MinByteLength
buffer.Printf("\nif(len([]byte(value)) < %d) {", cutoff)
buffer.AddIndentation(1)
buffer.Printf("\nreturn errors.New(\"Value's byte length is shorter than minimum length of %d\")", cutoff)
buffer.AddIndentation(-1)
buffer.Printf("\n}\n")
}
if schema.Pattern != nil {
buffer.Printf("\nmatched, err := regexp.Match(\"%s\", []byte(value))", sanitizeQuotedString(*schema.Pattern))
buffer.Printf("\nif(err != nil){return err}")
buffer.Printf("\nif(!matched) {")
buffer.AddIndentation(1)
buffer.Printf("\nreturn errors.New(\"Value did not match regex '%s'\")", *schema.Pattern)
buffer.AddIndentation(-1)
buffer.Print("\n}\n")
}
}
/*
Generates 'setter' code to validate the given array schema's constraints,
then set the owner object's value to the one passed in.
*/
func generateGoArraySetter(schema *ArraySchema, buffer *BufferedFormatString) {
if !schema.HasConstraints() {
return
}
buffer.Print("\nlength := len(value)\n")
if schema.MinItems != nil {
buffer.Printf("\nif(length < %d) {", *schema.MinItems)
buffer.AddIndentation(1)
buffer.Printf("\nreturn errors.New(\"Minimum number of elements '%d' not present\")", *schema.MinItems)
buffer.AddIndentation(-1)
buffer.Printf("\n}\n")
}
if schema.MaxItems != nil {
buffer.Printf("\nif(length > %d) {", *schema.MaxItems)
buffer.AddIndentation(1)
buffer.Printf("return errors.New(\"Maximum number of elements '%d' not present\")", *schema.MaxItems)
buffer.AddIndentation(-1)
buffer.Printf("\n}\n")
}
}
/*
Convenience method to generate an enum constraint check for the given schema and
its provided enum values.
Generates an inline set of constants, each value of which is prefixed and postfixed accordingly,
then generates code to check against those constants.
*/
func generateGoEnumForSchema(schema interface{}, buffer *BufferedFormatString, enumValues []interface{}, prefix string, postfix string) {
var length int
length = len(enumValues)
if length <= 0 {
return
}
// write array of valid values
buffer.Printf("\nvalidValues := []%s{%s%v%s", GenerateGoTypeForSchema(schema), prefix, enumValues[0], postfix)
for _, enumValue := range enumValues[1:length] {
buffer.Printf(",%s%v%s", prefix, enumValue, postfix)
}
buffer.Printf("}\n")
// compare
buffer.Printf("\nisValid := false")
buffer.Printf("\nfor _, validValue := range validValues {")
buffer.AddIndentation(1)
buffer.Printf("\nif(validValue == value){")
buffer.AddIndentation(1)
buffer.Printf("\nisValid = true\nbreak")
buffer.AddIndentation(-1)
buffer.Print("\n}\n")
buffer.Print("\nif(!isValid){")
buffer.AddIndentation(1)
buffer.Print("\nreturn errors.New(\"Given value was not found in list of acceptable values\")")
buffer.AddIndentation(-1)
buffer.Print("\n}\n")
buffer.AddIndentation(-1)
buffer.Print("\n}\n")
}
/*
Returns the Go equivalent of type for the given schema.
If no type is found, this returns "interface{}"
*/
func GenerateGoTypeForSchema(schema interface{}) string {
switch schema.(type) {
case *BooleanSchema:
return "bool"
case *StringSchema:
return "string"
case *IntegerSchema:
return "int"
case *NumberSchema:
return "float64"
case *ObjectSchema:
return "*" + ToCamelCase(schema.(TypeSchema).GetTitle())
case *ArraySchema:
return "[]" + GenerateGoTypeForSchema(schema.(*ArraySchema).Items)
}
return "interface{}"
}
/*
Generates a type variable declaration for the given schema and propertyName,
using the given casing function to modify the name of the property in the correct places.
*/
func generateVariableDeclaration(subschema TypeSchema, buffer *BufferedFormatString, propertyName string, casing func(string) string) {
var casedName string
casedName = ToJavaCase(propertyName)
// TODO: this means unexported fields will have json deserialization struct tags,
// which won't work.
buffer.Printf("\n%s %s", casing(propertyName), GenerateGoTypeForSchema(subschema))
buffer.Printf(" `json:\"%s\" xml:\"%s\" bson:\"%s\" codec:\"%s\"`", casedName, casedName, casedName, casedName)
}
/*
Determines and returns the appropriate case for the property of schema provided.
Only unconstrained fields are exported in Go generated code;
if the referenced field is constrained in any way, this generates an unexported field name.
*/
func getAppropriateGoCase(schema *ObjectSchema, propertyName string) string {
/*for _, constrainedName := range schema.ConstrainedProperties {
if constrainedName == propertyName {
return ToStrictJavaCase(propertyName)
}
}*/
return ToStrictCamelCase(propertyName)
}