-
Notifications
You must be signed in to change notification settings - Fork 1
/
codegen_js.go
412 lines (305 loc) · 10.8 KB
/
codegen_js.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
package presilo
import (
"fmt"
"regexp"
"strings"
)
/*
Generates valid JS code for a given schema.
*/
func GenerateJS(schema *ObjectSchema, module string, tabstyle string) string {
var buffer *BufferedFormatString
buffer = NewBufferedFormatString(tabstyle)
generateJSModuleCheck(buffer, module)
buffer.Print("\n")
generateJSConstructor(schema, buffer, module)
buffer.Print("\n")
generateJSDeserializer(schema, buffer, module)
buffer.Print("\n")
generateJSFunctions(schema, buffer, module)
buffer.Print("\n")
return buffer.String()
}
func ValidateJSModule(module string) bool {
// TODO: This implementation isn't strictly correct, but is probably best practice.
// In the future, may want to implement the below pattern
// (which we can't do right now because it requires Perl-flavor regex)
// ref: http://stackoverflow.com/a/9337047
pattern := "^[a-zA-Z_]+[0-9a-zA-Z_]*(\\.[a-zA-Z_]+[0-9a-zA-Z_]*)*$"
matched, err := regexp.MatchString(pattern, module)
return err == nil && matched
}
func generateJSModuleCheck(buffer *BufferedFormatString, module string) {
// check for undefined, first.
buffer.Printf("\nif(typeof(%s) === \"undefined\")\n{", module)
buffer.AddIndentation(1)
buffer.Printf("\n%s = {}", module)
buffer.AddIndentation(-1)
buffer.Print("\n}")
// then null check.
buffer.Print("\nelse\n{")
buffer.AddIndentation(1)
buffer.Printf("\n%s = %s || {}", module, module)
buffer.AddIndentation(-1)
buffer.Print("\n}\n")
}
func generateJSConstructor(schema *ObjectSchema, buffer *BufferedFormatString, module string) {
var parameterNames []string
var propertyName, parameterName string
// generate list of property names
for _, propertyName = range schema.RequiredProperties {
propertyName = ToJavaCase(propertyName)
parameterNames = append(parameterNames, propertyName)
}
// write constructor signature
buffer.Printf("\n/*\n%s\n*/\n", schema.Description)
buffer.Printf("\n%s.%s = function(", module, schema.Title)
buffer.Print(strings.Join(parameterNames, ","))
buffer.Print(")\n{")
buffer.AddIndentation(1)
// body
for _, parameterName = range parameterNames {
buffer.Printf("\nthis.set%s(%s)", ToStrictCamelCase(parameterName), parameterName)
}
buffer.AddIndentation(-1)
buffer.Print("\n}\n")
}
func generateJSDeserializer(schema *ObjectSchema, buffer *BufferedFormatString, module string) {
var property TypeSchema
var ctorArguments []string
var argument string
var className string
var propertyName, casedPropertyName string
className = ToCamelCase(schema.GetTitle())
buffer.Printf("\n%s.%s.deserializeFrom(map)", module, className)
buffer.Printf("\n{")
buffer.AddIndentation(1)
// use constructor
buffer.Printf("\nvar ret = new %s.%s(", module, className)
for _, propertyName = range schema.RequiredProperties {
argument = fmt.Sprintf("map[\"%s\"]", ToJavaCase(propertyName))
ctorArguments = append(ctorArguments, argument)
}
buffer.Printf("%s)", strings.Join(ctorArguments, ", "))
// misc setters
buffer.Printf("\n")
for _, propertyName = range schema.GetOrderedPropertyNames() {
property = schema.Properties[propertyName]
propertyName = ToJavaCase(property.GetTitle())
casedPropertyName = fmt.Sprintf("map[\"%s\"]", propertyName)
// if it's already set, skip it.
if arrayContainsString(ctorArguments, casedPropertyName) {
continue
}
// if it's constrained, use the setter
if property.HasConstraints() {
casedPropertyName = ToJavaCase(propertyName)
buffer.Printf("\nret.set%s(map[\"%s\"])", ToStrictCamelCase(propertyName), casedPropertyName)
continue
}
// otherwise set.
buffer.Printf("\nret.%s = %s", propertyName, casedPropertyName)
}
buffer.Printf("\nreturn ret")
buffer.AddIndentation(-1)
buffer.Printf("\n}\n")
}
func generateJSFunctions(schema *ObjectSchema, buffer *BufferedFormatString, module string) {
var subschema TypeSchema
var propertyName, propertyNameCamel, propertyNameJava, schemaName string
schemaName = ToCamelCase(schema.Title)
for propertyName, subschema = range schema.Properties {
propertyNameCamel = ToStrictCamelCase(propertyName)
propertyNameJava = ToJavaCase(propertyName)
buffer.Printf("\n%s.%s.prototype.set%s = function(value)\n{", module, schemaName, propertyNameCamel)
buffer.AddIndentation(1)
// undefined check
buffer.Printf("\nif(typeof(value) === 'undefined')\n{")
buffer.AddIndentation(1)
buffer.Printf("\nthrow new ReferenceError(\"Cannot set property '%s', no value given\")", propertyNameJava)
buffer.AddIndentation(-1)
buffer.Print("\n}\n")
switch subschema.GetSchemaType() {
case SCHEMATYPE_STRING:
generateJSStringSetter(subschema.(*StringSchema), buffer)
case SCHEMATYPE_INTEGER:
fallthrough
case SCHEMATYPE_NUMBER:
generateJSNumericSetter(subschema.(NumericSchemaType), buffer)
case SCHEMATYPE_OBJECT:
generateJSObjectSetter(subschema.(*ObjectSchema), buffer)
case SCHEMATYPE_ARRAY:
generateJSArraySetter(subschema.(*ArraySchema), buffer)
}
buffer.Printf("\nthis.%s = value;", propertyNameJava)
buffer.AddIndentation(-1)
buffer.Print("\n}\n")
}
}
/*
Returns checks appropriate for verifying an object's type.
*/
func generateJSObjectSetter(schema *ObjectSchema, buffer *BufferedFormatString) {
generateJSTypeCheck(schema, buffer)
}
/*
Returns checks appropriate for verifying a numeric value and its constraints.
*/
func generateJSNumericSetter(schema NumericSchemaType, buffer *BufferedFormatString) {
generateJSTypeCheck(schema, buffer)
if schema.HasMinimum() {
generateJSRangeCheck(schema.GetMinimum(), "value", schema.GetConstraintFormat(), schema.IsExclusiveMinimum(), "<=", "<", buffer)
}
if schema.HasMaximum() {
generateJSRangeCheck(schema.GetMaximum(), "value", schema.GetConstraintFormat(), schema.IsExclusiveMaximum(), ">=", ">", buffer)
}
if schema.HasEnum() {
generateJSEnumCheck(schema, buffer, schema.GetEnum(), "", "")
}
if schema.HasMultiple() {
buffer.Printf("\nif(value %% %f != 0)\n{", schema.GetMultiple())
buffer.AddIndentation(1)
buffer.Printf("\nthrow new Error(\"Property '\"+value+\"' was not a multiple of %s\")", schema.GetMultiple())
buffer.AddIndentation(-1)
buffer.Print("\n}\n")
}
}
/*
Returns checks appropriate for verifying a string value and its constraints.
*/
func generateJSStringSetter(schema *StringSchema, buffer *BufferedFormatString) {
generateJSTypeCheck(schema, buffer)
if schema.MinLength != nil {
generateJSRangeCheck(*schema.MinLength, "value.length", "%d", false, "<", "", buffer)
}
if schema.MaxLength != nil {
generateJSRangeCheck(*schema.MaxLength, "value.length", "%d", false, ">", "", buffer)
}
if schema.Pattern != nil {
buffer.Printf("\nvar regex = new RegExp(\"%s\")", *schema.Pattern)
buffer.Printf("\nif(!regex.test(value))\n{")
buffer.AddIndentation(1)
buffer.Printf("\nthrow new Error(\"Property '\"+value+\"' did not match pattern '%s'\")", *schema.Pattern)
buffer.AddIndentation(-1)
buffer.Print("\n}\n")
}
if schema.Enum != nil {
generateJSEnumCheck(schema, buffer, schema.GetEnum(), "\"", "\"")
}
}
/*
Returns checks appropriate for verifying an array value and its constraints.
*/
func generateJSArraySetter(schema *ArraySchema, buffer *BufferedFormatString) {
generateJSTypeCheck(schema, buffer)
// TODO: value uniformity check
if schema.MinItems != nil {
generateJSRangeCheck(*schema.MinItems, "value.length", "%d", false, "<", "", buffer)
}
if schema.MaxItems != nil {
generateJSRangeCheck(*schema.MaxItems, "value.length", "%d", false, ">", "", buffer)
}
}
func generateJSRangeCheck(value interface{}, reference string, format string, exclusive bool, comparator, exclusiveComparator string, buffer *BufferedFormatString) {
var compareString string
if exclusive {
compareString = exclusiveComparator
} else {
compareString = comparator
}
buffer.Printf("\nif(%s %s "+format+")\n{", reference, compareString, value)
buffer.AddIndentation(1)
buffer.Printf("\nthrow new RangeError(\"Property '\"+value+\"' was out of range.\")")
buffer.AddIndentation(-1)
buffer.Print("\n}\n")
}
/*
Generates code which throws an error if the given [parameter]'s type name is not equal to the given [typeName]
*/
func generateJSTypeCheck(schema TypeSchema, buffer *BufferedFormatString) {
var schemaType SchemaType
var expectedType string
var shouldWriteCtorCheck bool
schemaType = schema.GetSchemaType()
expectedType = getJSTypeFromSchemaType(schemaType)
if schema.GetNullable() {
buffer.Printf("\nif(value != null)\n{")
buffer.AddIndentation(1)
}
buffer.Printf("\nif(typeof(value) !== \"%s\")\n{", expectedType)
buffer.AddIndentation(1)
buffer.Printf("\nthrow new TypeError(\"Property \"+value+\" was not of the expected type '%s'\")", expectedType)
buffer.AddIndentation(-1)
buffer.Print("\n}\n")
// if this is an array or object, check the constructor
shouldWriteCtorCheck = false
switch schemaType {
case SCHEMATYPE_ARRAY:
shouldWriteCtorCheck = true
expectedType = "Array"
case SCHEMATYPE_OBJECT:
shouldWriteCtorCheck = true
expectedType = ToCamelCase(schema.GetTitle())
}
if shouldWriteCtorCheck {
buffer.Printf("\nif(value.constructor !== %s)\n{", expectedType)
buffer.AddIndentation(1)
buffer.Printf("\nthrow new TypeError(\"Property '\"+value+\"'was not of the expected type '%s'\")", expectedType)
buffer.AddIndentation(-1)
buffer.Print("\n}\n")
}
if schema.GetNullable() {
buffer.AddIndentation(-1)
buffer.Printf("\n}")
}
}
/*
Generates code which throws an error if the given [parameter]'s value is not contained in the given [validValues].
*/
func generateJSEnumCheck(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("\nvar validValues = [%s%v%s", prefix, enumValues[0], postfix)
for _, enumValue := range enumValues[1:length] {
buffer.Printf(",%s%v%s", prefix, enumValue, postfix)
}
buffer.Print("]\n")
// compare
buffer.Print("\nvar isValid = false")
buffer.Print("\nfor(var i = 0; i < validValues.length; i++) \n{")
buffer.AddIndentation(1)
buffer.Print("\nif(validValues[i] === value)\n{")
buffer.AddIndentation(1)
buffer.Print("\nisValid = true")
buffer.Print("\nbreak;")
buffer.AddIndentation(-1)
buffer.Print("\n}")
buffer.AddIndentation(-1)
buffer.Print("\n}")
buffer.Print("\nif(!isValid)\n{")
buffer.AddIndentation(1)
buffer.Print("\nthrow new Error(\"Given value '\"+value+\"' was not found in list of acceptable values\")")
buffer.AddIndentation(-1)
buffer.Print("\n}")
}
func getJSTypeFromSchemaType(schemaType SchemaType) string {
switch schemaType {
case SCHEMATYPE_NUMBER:
fallthrough
case SCHEMATYPE_INTEGER:
return "number"
case SCHEMATYPE_ARRAY:
fallthrough
case SCHEMATYPE_OBJECT:
return "object"
case SCHEMATYPE_STRING:
return "string"
case SCHEMATYPE_BOOLEAN:
return "boolean"
}
return "object"
}