/
helper.go
451 lines (413 loc) · 11.6 KB
/
helper.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
package generator
import (
"fmt"
"strconv"
"strings"
"unicode"
"github.com/golang/protobuf/protoc-gen-go/descriptor"
)
// And now lots of helper functions.
// Is c an ASCII lower-case letter?
func isASCIILower(c byte) bool {
return 'a' <= c && c <= 'z'
}
// Is c an ASCII upper-case letter?
func isASCIIUpper(c byte) bool {
return 'A' <= c && c <= 'Z'
}
// Is c an ASCII digit?
func isASCIIDigit(c byte) bool {
return '0' <= c && c <= '9'
}
// CamelCase returns the CamelCased name.
func CamelCase(s string) string {
if s == "" {
return ""
}
t := make([]byte, 0, 32)
i := 0
// Invariant: if the next letter is lower case, it must be converted
// to upper case.
// That is, we process a word at a time, where words are marked by _ or
// upper case letter. Digits are treated as words.
for ; i < len(s); i++ {
c := s[i]
if c == '_' && i+1 < len(s) && isASCIILower(s[i+1]) {
continue // Skip the underscore in s.
}
if isASCIIDigit(c) {
t = append(t, c)
continue
}
// Assume we have a letter now - if not, it's a bogus identifier.
// The next word is a sequence of characters that must start upper case.
if isASCIILower(c) {
c ^= ' ' // Make it a capital letter.
}
t = append(t, c) // Guaranteed not lower case.
// Accept lower case sequence that follows.
for i+1 < len(s) && isASCIILower(s[i+1]) {
i++
t = append(t, s[i])
}
}
if isASCIIUpper(t[0]) {
t[0] ^= ' '
}
return string(t)
}
// CamelCaseSlice is like CamelCase, but the argument is a slice of strings to
// be joined with "_".
func CamelCaseSlice(elem []string) string { return CamelCase(strings.Join(elem, "_")) }
// dottedSlice turns a sliced name into a dotted name.
func dottedSlice(elem []string) string { return strings.Join(elem, ".") }
// Is this field optional?
func isOptional(field *descriptor.FieldDescriptorProto) bool {
return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_OPTIONAL
}
// Is this field required?
func isRequired(field *descriptor.FieldDescriptorProto) bool {
return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REQUIRED
}
// Is this field repeated?
func isRepeated(field *descriptor.FieldDescriptorProto) bool {
return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REPEATED
}
// Is this field a scalar numeric type?
func isScalar(field *descriptor.FieldDescriptorProto) bool {
if field.Type == nil {
return false
}
switch *field.Type {
case descriptor.FieldDescriptorProto_TYPE_DOUBLE,
descriptor.FieldDescriptorProto_TYPE_FLOAT,
descriptor.FieldDescriptorProto_TYPE_INT64,
descriptor.FieldDescriptorProto_TYPE_UINT64,
descriptor.FieldDescriptorProto_TYPE_INT32,
descriptor.FieldDescriptorProto_TYPE_FIXED64,
descriptor.FieldDescriptorProto_TYPE_FIXED32,
descriptor.FieldDescriptorProto_TYPE_BOOL,
descriptor.FieldDescriptorProto_TYPE_UINT32,
descriptor.FieldDescriptorProto_TYPE_SFIXED32,
descriptor.FieldDescriptorProto_TYPE_SFIXED64,
descriptor.FieldDescriptorProto_TYPE_SINT32,
descriptor.FieldDescriptorProto_TYPE_SINT64:
return true
default:
return false
}
}
// paramToJavaPackage convert parameter to a valid java package name
func paramToJavaPackage(param string) string {
if param == "" {
return ""
}
param = strings.ToLower(param)
for strings.HasPrefix(param, ".") {
param = strings.TrimPrefix(param, ".")
}
for strings.HasSuffix(param, ".") {
param = strings.TrimSuffix(param, ".")
}
return param
}
// javaType returns a string representing the type name, and the wire type
func javaType(field *descriptor.FieldDescriptorProto) (typeName, defaultValue string) {
repeat := isRepeated(field)
isOneOf := field.OneofIndex != nil
defaultValue = "null"
switch *field.Type {
case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
if repeat {
typeName = "List<Double>"
defaultValue = "new ArrayList<>()"
} else {
typeName = "double"
defaultValue = "0.0"
}
if isOneOf {
defaultValue = "null"
if !repeat {
typeName = "Double"
}
}
case descriptor.FieldDescriptorProto_TYPE_FLOAT:
if repeat {
typeName = "List<Float>"
defaultValue = "new ArrayList<>()"
} else {
typeName = "float"
defaultValue = "0f"
}
if isOneOf {
defaultValue = "null"
if !repeat {
typeName = "Float"
}
}
case descriptor.FieldDescriptorProto_TYPE_INT64:
fallthrough
case descriptor.FieldDescriptorProto_TYPE_UINT64:
fallthrough
case descriptor.FieldDescriptorProto_TYPE_SFIXED64:
fallthrough
case descriptor.FieldDescriptorProto_TYPE_SINT64:
fallthrough
case descriptor.FieldDescriptorProto_TYPE_FIXED64:
if repeat {
typeName = "List<Long>"
defaultValue = "new ArrayList<>()"
} else {
typeName = "long"
defaultValue = "0L"
}
if isOneOf {
defaultValue = "null"
if !repeat {
typeName = "Long"
}
}
case descriptor.FieldDescriptorProto_TYPE_INT32:
fallthrough
case descriptor.FieldDescriptorProto_TYPE_UINT32:
fallthrough
case descriptor.FieldDescriptorProto_TYPE_FIXED32:
fallthrough
case descriptor.FieldDescriptorProto_TYPE_SFIXED32:
fallthrough
case descriptor.FieldDescriptorProto_TYPE_SINT32:
if repeat {
typeName = "List<Integer>"
defaultValue = "new ArrayList<>()"
} else {
typeName = "int"
defaultValue = "0"
}
if isOneOf {
defaultValue = "null"
if !repeat {
typeName = "Integer"
}
}
case descriptor.FieldDescriptorProto_TYPE_BOOL:
if repeat {
typeName = "List<Boolean>"
defaultValue = "new ArrayList<>()"
} else {
typeName = "boolean"
defaultValue = "false"
}
if isOneOf {
defaultValue = "null"
if !repeat {
typeName = "Boolean"
}
}
case descriptor.FieldDescriptorProto_TYPE_STRING:
if repeat {
typeName = "List<String>"
defaultValue = "new ArrayList<>()"
} else {
typeName = "String"
defaultValue = "\"\""
}
if isOneOf {
defaultValue = "null"
}
case descriptor.FieldDescriptorProto_TYPE_BYTES:
if repeat {
typeName = "List<byte[]>"
defaultValue = "new ArrayList<>()"
} else {
typeName = "byte[]"
defaultValue = "new byte[]{}"
}
if isOneOf {
defaultValue = "null"
}
}
return
}
// kotlinType returns a string representing the type name, and the wire type
func kotlinType(field *descriptor.FieldDescriptorProto) (typeName, defaultValue string) {
repeat := isRepeated(field)
switch *field.Type {
case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
if repeat {
typeName = "DoubleArray"
defaultValue = "doubleArrayOf()"
} else {
typeName = "Double"
defaultValue = "0.0"
}
case descriptor.FieldDescriptorProto_TYPE_FLOAT:
if repeat {
typeName = "FloatArray"
defaultValue = "floatArrayOf()"
} else {
typeName = "Float"
defaultValue = "0f"
}
case descriptor.FieldDescriptorProto_TYPE_INT64:
fallthrough
case descriptor.FieldDescriptorProto_TYPE_UINT64:
fallthrough
case descriptor.FieldDescriptorProto_TYPE_SFIXED64:
fallthrough
case descriptor.FieldDescriptorProto_TYPE_SINT64:
fallthrough
case descriptor.FieldDescriptorProto_TYPE_FIXED64:
if repeat {
typeName = "LongArray"
defaultValue = "longArrayOf()"
} else {
typeName = "Long"
defaultValue = "0L"
}
case descriptor.FieldDescriptorProto_TYPE_INT32:
fallthrough
case descriptor.FieldDescriptorProto_TYPE_UINT32:
fallthrough
case descriptor.FieldDescriptorProto_TYPE_FIXED32:
fallthrough
case descriptor.FieldDescriptorProto_TYPE_SFIXED32:
fallthrough
case descriptor.FieldDescriptorProto_TYPE_SINT32:
if repeat {
typeName = "IntArray"
defaultValue = "intArrayOf()"
} else {
typeName = "Int"
defaultValue = "0"
}
case descriptor.FieldDescriptorProto_TYPE_BOOL:
if repeat {
typeName = "BooleanArray"
defaultValue = "booleanArrayOf()"
} else {
typeName = "Boolean"
defaultValue = "false"
}
case descriptor.FieldDescriptorProto_TYPE_STRING:
if repeat {
typeName = "List<String>"
defaultValue = "listOf()"
} else {
typeName = "String"
defaultValue = "\"\""
}
case descriptor.FieldDescriptorProto_TYPE_BYTES:
typeName = "ByteArray"
defaultValue = "byteArrayOf()"
}
return
}
func javaFieldName(field *descriptor.FieldDescriptorProto) string {
return CamelCase(field.GetName())
}
// javaConverterName return java protobuf converter class name
func javaConverterName(file *FileDescriptor) string {
javaClsName := ""
if file.GetOptions() != nil && file.GetOptions().GetJavaOuterClassname() != "" {
javaClsName = file.GetOptions().GetJavaOuterClassname()
} else {
javaClsName = file.GetPackage()
parts := strings.Split(javaClsName, ".")
javaClsName = parts[len(parts)-1]
}
if strings.HasPrefix(strings.ToLower(javaClsName), "pb") {
javaClsName = javaClsName[2:]
}
javaClsName = strings.Title(javaClsName)
return fmt.Sprintf("%sPb2JavaBean", javaClsName)
}
// badToUnderscore is the mapping function used to generate Go names from package names,
// which can be dotted in the input .proto file. It replaces non-identifier characters such as
// dot or dash with underscore.
func badToUnderscore(r rune) rune {
if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' {
return r
}
return '_'
}
// baseName returns the last path element of the name, with the last dotted suffix removed.
func baseName(name string) string {
// First, find the last element
if i := strings.LastIndex(name, "/"); i >= 0 {
name = name[i+1:]
}
// Now drop the suffix
if i := strings.LastIndex(name, "."); i >= 0 {
name = name[0:i]
}
return name
}
func cleanPackageName(name string) JavaPackageName {
// name = strings.Map(badToUnderscore, name)
// // Identifier must not be keyword or predeclared identifier: insert _.
// if isGoKeyword[name] {
// name = "_" + name
// }
// // Identifier must not begin with digit: insert _.
// if r, _ := utf8.DecodeRuneInString(name); unicode.IsDigit(r) {
// name = "_" + name
// }
return JavaPackageName(name)
}
var escapeChars = [256]byte{
'a': '\a', 'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t', 'v': '\v', '\\': '\\', '"': '"', '\'': '\'', '?': '?',
}
// unescape reverses the "C" escaping that protoc does for default values of bytes fields.
// It is best effort in that it effectively ignores malformed input. Seemingly invalid escape
// sequences are conveyed, unmodified, into the decoded result.
func unescape(s string) string {
// NB: Sadly, we can't use strconv.Unquote because protoc will escape both
// single and double quotes, but strconv.Unquote only allows one or the
// other (based on actual surrounding quotes of its input argument).
var out []byte
for len(s) > 0 {
// regular character, or too short to be valid escape
if s[0] != '\\' || len(s) < 2 {
out = append(out, s[0])
s = s[1:]
} else if c := escapeChars[s[1]]; c != 0 {
// escape sequence
out = append(out, c)
s = s[2:]
} else if s[1] == 'x' || s[1] == 'X' {
// hex escape, e.g. "\x80
if len(s) < 4 {
// too short to be valid
out = append(out, s[:2]...)
s = s[2:]
continue
}
v, err := strconv.ParseUint(s[2:4], 16, 8)
if err != nil {
out = append(out, s[:4]...)
} else {
out = append(out, byte(v))
}
s = s[4:]
} else if '0' <= s[1] && s[1] <= '7' {
// octal escape, can vary from 1 to 3 octal digits; e.g., "\0" "\40" or "\164"
// so consume up to 2 more bytes or up to end-of-string
n := len(s[1:]) - len(strings.TrimLeft(s[1:], "01234567"))
if n > 3 {
n = 3
}
v, err := strconv.ParseUint(s[1:1+n], 8, 8)
if err != nil {
out = append(out, s[:1+n]...)
} else {
out = append(out, byte(v))
}
s = s[1+n:]
} else {
// bad escape, just propagate the slash as-is
out = append(out, s[0])
s = s[1:]
}
}
return string(out)
}