aboutsummaryrefslogtreecommitdiffstats
path: root/binapigen/gen_encoding.go
blob: ca1e8486de18c82edc6f48102414faa9b7a905b7 (plain)
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
//  Copyright (c) 2020 Cisco and/or its affiliates.
//
//  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 binapigen

import (
	"fmt"
	"strconv"

	"github.com/sirupsen/logrus"
)

func genMessageSize(g *GenFile, name string, fields []*Field) {
	g.P("func (m *", name, ") Size() (size int) {")
	g.P("if m == nil { return 0 }")

	sizeBaseType := func(typ, name string, length int, sizefrom string) {
		switch typ {
		case STRING:
			if length > 0 {
				g.P("size += ", length, " // ", name)
			} else {
				g.P("size += 4 + len(", name, ")", " // ", name)
			}
		default:
			var size = BaseTypeSizes[typ]
			if sizefrom != "" {
				g.P("size += ", size, " * len(", name, ")", " // ", name)
			} else {
				if length > 0 {
					g.P("size += ", size, " * ", length, " // ", name)
				} else {
					g.P("size += ", size, " // ", name)
				}
			}
		}
	}

	lvl := 0
	var sizeFields func(fields []*Field, parentName string)
	sizeFields = func(fields []*Field, parentName string) {
		lvl++
		defer func() { lvl-- }()

		getFieldName := func(name string) string {
			return fmt.Sprintf("%s.%s", parentName, name)
		}

		for _, field := range fields {
			name := getFieldName(field.GoName)

			var sizeFromName string
			if field.FieldSizeFrom != nil {
				sizeFromName = getFieldName(field.FieldSizeFrom.GoName)
			}

			if _, ok := BaseTypesGo[field.Type]; ok {
				sizeBaseType(field.Type, name, field.Length, sizeFromName)
				continue
			}

			if field.Array {
				index := fmt.Sprintf("j%d", lvl)
				if field.Length > 0 {
					g.P("for ", index, " := 0; ", index, " < ", field.Length, "; ", index, "++ {")
				} else if field.FieldSizeFrom != nil {
					g.P("for ", index, " := 0; ", index, " < len(", name, "); ", index, "++ {")
				}
				if field.Length == 0 || field.SizeFrom != "" {
					char := fmt.Sprintf("s%d", lvl)
					g.P("var ", char, " ", fieldGoType(g, field))
					g.P("_ = ", char)
					g.P("if ", index, " < len(", name, ") { ", char, " = ", name, "[", index, "] }")
					name = char
				} else {
					name = fmt.Sprintf("%s[%s]", name, index)
				}
			}

			switch {
			case field.TypeEnum != nil:
				enum := field.TypeEnum
				if _, ok := BaseTypesGo[enum.Type]; ok {
					sizeBaseType(enum.Type, name, 0, "")
				} else {
					logrus.Panicf("\t// ??? ENUM %s %s\n", name, enum.Type)
				}
			case field.TypeAlias != nil:
				alias := field.TypeAlias
				if typ := alias.TypeStruct; typ != nil {
					sizeFields(typ.Fields, name)
				} else {
					sizeBaseType(alias.Type, name, alias.Length, "")
				}
			case field.TypeStruct != nil:
				typ := field.TypeStruct
				sizeFields(typ.Fields, name)
			case field.TypeUnion != nil:
				union := field.TypeUnion
				maxSize := getUnionSize(union)
				sizeBaseType("u8", name, maxSize, "")
			default:
				logrus.Panicf("\t// ??? buf[pos] = %s (%s)\n", name, field.Type)
			}

			if field.Array {
				g.P("}")
			}
		}
	}
	sizeFields(fields, "m")

	g.P("return size")
	g.P("}")
}

func genMessageMarshal(g *GenFile, name string, fields []*Field) {
	g.P("func (m *", name, ") Marshal(b []byte) ([]byte, error) {")
	g.P("if b == nil {")
	g.P("b = make([]byte, m.Size())")
	g.P("}")
	g.P("buf := ", govppCodecPkg.Ident("NewBuffer"), "(b)")

	encodeFields(g, fields, "m", 0)

	g.P("return buf.Bytes(), nil")
	g.P("}")
}

func encodeFields(g *GenFile, fields []*Field, parentName string, lvl int) {
	getFieldName := func(name string) string {
		return fmt.Sprintf("%s.%s", parentName, name)
	}

	for _, field := range fields {
		name := getFieldName(field.GoName)

		encodeField(g, field, name, getFieldName, lvl)
	}
}

func encodeField(g *GenFile, field *Field, name string, getFieldName func(name string) string, lvl int) {
	if f := field.FieldSizeOf; f != nil {
		if _, ok := BaseTypesGo[field.Type]; ok {
			val := fmt.Sprintf("len(%s)", getFieldName(f.GoName))
			encodeBaseType(g, field.Type, "int", val, 0, "", false)
			return
		} else {
			panic(fmt.Sprintf("failed to encode base type of sizefrom field: %s (%s)", field.Name, field.Type))
		}
	}
	var sizeFromName string
	if field.FieldSizeFrom != nil {
		sizeFromName = getFieldName(field.FieldSizeFrom.GoName)
	}

	if _, ok := BaseTypesGo[field.Type]; ok {
		encodeBaseType(g, field.Type, fieldGoType(g, field), name, field.Length, sizeFromName, true)
		return
	}

	if field.Array {
		index := fmt.Sprintf("j%d", lvl)
		if field.Length > 0 {
			g.P("for ", index, " := 0; ", index, " < ", field.Length, "; ", index, "++ {")
		} else if field.SizeFrom != "" {
			g.P("for ", index, " := 0; ", index, " < len(", name, "); ", index, "++ {")
		}
		if field.Length == 0 || field.SizeFrom != "" {
			char := fmt.Sprintf("v%d", lvl)
			g.P("var ", char, " ", fieldGoType(g, field), "// ", field.GoName)
			g.P("if ", index, " < len(", name, ") { ", char, " = ", name, "[", index, "] }")
			name = char
		} else {
			name = fmt.Sprintf("%s[%s]", name, index)
		}
	}

	switch {
	case field.TypeEnum != nil:
		encodeBaseType(g, field.TypeEnum.Type, fieldGoType(g, field), name, 0, "", false)
	case field.TypeAlias != nil:
		alias := field.TypeAlias
		if typ := alias.TypeStruct; typ != nil {
			encodeFields(g, typ.Fields, name, lvl+1)
		} else {
			if alias.Length > 0 {
				encodeBaseType(g, alias.Type, BaseTypesGo[alias.Type], name, alias.Length, "", false)
			} else {
				encodeBaseType(g, alias.Type, fieldGoType(g, field), name, 0, "", false)
			}
		}
	case field.TypeStruct != nil:
		encodeFields(g, field.TypeStruct.Fields, name, lvl+1)
	case field.TypeUnion != nil:
		maxSize := getUnionSize(field.TypeUnion)
		g.P("buf.EncodeBytes(", name, ".", fieldUnionData, "[:], ", maxSize, ")")
	default:
		logrus.Panicf("\t// ??? buf[pos] = %s (%s)\n", name, field.Type)
	}

	if field.Array {
		g.P("}")
	}
}

func encodeBaseType(g *GenFile, typ, orig, name string, length int, sizefrom string, alloc bool) {
	isArray := length > 0 || sizefrom != ""
	if isArray {
		switch typ {
		case U8:
			if alloc {
				g.P("buf.EncodeBytes(", name, ", ", length, ")")
			} else {
				g.P("buf.EncodeBytes(", name, "[:], ", length, ")")
			}
			return
		case I8, I16, U16, I32, U32, I64, U64, F64, BOOL:
			gotype := BaseTypesGo[typ]
			if length != 0 {
				g.P("for i := 0; i < ", length, "; i++ {")
			} else if sizefrom != "" {
				g.P("for i := 0; i < len(", name, "); i++ {")
			}
			if alloc {
				g.P("var x ", gotype)
				g.P("if i < len(", name, ") { x = ", gotype, "(", name, "[i]) }")
				name = "x"
			}
		}
	}
	conv := func(s string) string {
		if gotype, ok := BaseTypesGo[typ]; !ok || gotype != orig {
			return fmt.Sprintf("%s(%s)", gotype, s)
		}
		return s
	}
	switch typ {
	case I8, I16, I32, I64:
		typsize := BaseTypeSizes[typ]
		g.P("buf.EncodeInt", typsize*8, "(", conv(name), ")")
	case U8, U16, U32, U64:
		typsize := BaseTypeSizes[typ]
		g.P("buf.EncodeUint", typsize*8, "(", conv(name), ")")
	case F64:
		g.P("buf.EncodeFloat64(", conv(name), ")")
	case BOOL:
		g.P("buf.EncodeBool(", name, ")")
	case STRING:
		g.P("buf.EncodeString(", name, ", ", length, ")")
	default:
		logrus.Panicf("// ??? %s %s\n", name, typ)
	}
	if isArray {
		switch typ {
		case I8, U8, I16, U16, I32, U32, I64, U64, F64, BOOL:
			g.P("}")
		}
	}
}

func genMessageUnmarshal(g *GenFile, name string, fields []*Field) {
	g.P("func (m *", name, ") Unmarshal(b []byte) error {")

	if len(fields) > 0 {
		g.P("buf := ", govppCodecPkg.Ident("NewBuffer"), "(b)")
		decodeFields(g, fields, "m", 0)
	}

	g.P("return nil")
	g.P("}")
}

func decodeFields(g *GenFile, fields []*Field, parentName string, lvl int) {
	getFieldName := func(name string) string {
		return fmt.Sprintf("%s.%s", parentName, name)
	}

	for _, field := range fields {
		name := getFieldName(field.GoName)

		decodeField(g, field, name, getFieldName, lvl)
	}
}

func decodeField(g *GenFile, field *Field, name string, getFieldName func(string) string, lvl int) {
	var sizeFromName string
	if field.FieldSizeFrom != nil {
		sizeFromName = getFieldName(field.FieldSizeFrom.GoName)
	}

	if _, ok := BaseTypesGo[field.Type]; ok {
		decodeBaseType(g, field.Type, fieldGoType(g, field), name, field.Length, sizeFromName, true)
		return
	}

	if field.Array {
		index := fmt.Sprintf("j%d", lvl)
		if field.Length > 0 {
			g.P("for ", index, " := 0; ", index, " < ", field.Length, ";", index, "++ {")
		} else if field.SizeFrom != "" {
			g.P(name, " = make(", getFieldType(g, field), ", ", sizeFromName, ")")
			g.P("for ", index, " := 0; ", index, " < len(", name, ");", index, "++ {")
		}
		name = fmt.Sprintf("%s[%s]", name, index)
	}

	if enum := field.TypeEnum; enum != nil {
		if _, ok := BaseTypesGo[enum.Type]; ok {
			decodeBaseType(g, enum.Type, fieldGoType(g, field), name, 0, "", false)
		} else {
			logrus.Panicf("\t// ??? ENUM %s %s\n", name, enum.Type)
		}
	} else if alias := field.TypeAlias; alias != nil {
		if typ := alias.TypeStruct; typ != nil {
			decodeFields(g, typ.Fields, name, lvl+1)
		} else {
			if alias.Length > 0 {
				decodeBaseType(g, alias.Type, BaseTypesGo[alias.Type], name, alias.Length, "", false)
			} else {
				decodeBaseType(g, alias.Type, fieldGoType(g, field), name, 0, "", false)
			}
		}
	} else if typ := field.TypeStruct; typ != nil {
		decodeFields(g, typ.Fields, name, lvl+1)
	} else if union := field.TypeUnion; union != nil {
		maxSize := getUnionSize(union)
		g.P("copy(", name, ".", fieldUnionData, "[:], buf.DecodeBytes(", maxSize, "))")
	} else {
		logrus.Panicf("\t// ??? %s (%v)\n", field.GoName, field.Type)
	}

	if field.Array {
		g.P("}")
	}
}

func decodeBaseType(g *GenFile, typ, orig, name string, length int, sizefrom string, alloc bool) {
	isArray := length > 0 || sizefrom != ""
	if isArray {
		var size string
		switch {
		case length > 0:
			size = strconv.Itoa(length)
		case sizefrom != "":
			size = sizefrom
		}
		switch typ {
		case U8:
			if alloc {
				g.P(name, " = make([]byte, ", size, ")")
				g.P("copy(", name, ", buf.DecodeBytes(len(", name, ")))")
			} else {
				g.P("copy(", name, "[:], buf.DecodeBytes(", size, "))")
			}
			return
		case I8, I16, U16, I32, U32, I64, U64, F64, BOOL:
			if alloc {
				g.P(name, " = make([]", orig, ", ", size, ")")
			}
			g.P("for i := 0; i < len(", name, "); i++ {")
			name = fmt.Sprintf("%s[i]", name)
		}
	}
	conv := func(s string) string {
		if gotype, ok := BaseTypesGo[typ]; !ok || gotype != orig {
			return fmt.Sprintf("%s(%s)", orig, s)
		}
		return s
	}
	switch typ {
	case I8, I16, I32, I64:
		typsize := BaseTypeSizes[typ]
		g.P(name, " = ", conv(fmt.Sprintf("buf.DecodeInt%d()", typsize*8)))
	case U8, U16, U32, U64:
		typsize := BaseTypeSizes[typ]
		g.P(name, " = ", conv(fmt.Sprintf("buf.DecodeUint%d()", typsize*8)))
	case F64:
		g.P(name, " = ", conv("buf.DecodeFloat64()"))
	case BOOL:
		g.P(name, " = buf.DecodeBool()")
	case STRING:
		g.P(name, " = buf.DecodeString(", length, ")")
	default:
		logrus.Panicf("\t// ??? %s %s\n", name, typ)
	}
	if isArray {
		switch typ {
		case I8, U8, I16, U16, I32, U32, I64, U64, F64, BOOL:
			g.P("}")
		}
	}
}