Debian Codegraph @

tools/golang/xenlight/gengotypes.py

raw
1 #!/usr/bin/python
2
3 from __future__ import print_function
4
5 import os
6 import sys
7
8 try:
9 sys.path.append(os.environ['LIBXL_SRC_DIR'])
10 except:
11 # If we get here, then we expect the 'import idl'
12 # expression to fail. That error is more informative,
13 # so let it happen.
14 pass
15
16 import idl
17
18 # Go versions of some builtin types.
19 # Append the libxl-defined builtins after IDL parsing.
20 builtin_type_names = {
21 idl.bool.typename: 'bool',
22 idl.string.typename: 'string',
23 idl.integer.typename: 'int',
24 idl.uint8.typename: 'byte',
25 idl.uint16.typename: 'uint16',
26 idl.uint32.typename: 'uint32',
27 idl.uint64.typename: 'uint64',
28 }
29
30 # Some go keywords that conflict with field names in libxl structs.
31 go_keywords = ['type', 'func']
32
33 go_builtin_types = ['bool', 'string', 'int', 'byte',
34 'uint16', 'uint32', 'uint64']
35
36 # cgo preamble for xenlight_helpers.go, created during type generation and
37 # written later.
38 cgo_helpers_preamble = []
39
40 def xenlight_golang_generate_types(path = None, types = None, comment = None):
41 """
42 Generate a .go file (types.gen.go by default)
43 that contains a Go type for each type in types.
44 """
45 if path is None:
46 path = 'types.gen.go'
47
48 with open(path, 'w') as f:
49 if comment is not None:
50 f.write(comment)
51 f.write('package xenlight\n\n')
52
53 for ty in types:
54 (tdef, extras) = xenlight_golang_type_define(ty)
55
56 f.write(tdef)
57 f.write('\n')
58
59 # Append extra types
60 for extra in extras:
61 f.write(extra)
62 f.write('\n')
63
64 def xenlight_golang_type_define(ty = None):
65 """
66 Generate the Go type definition of ty.
67
68 Return a tuple that contains a string with the
69 type definition, and a (potentially empty) list
70 of extra definitions that are associated with
71 this type.
72 """
73 if isinstance(ty, idl.Enumeration):
74 return (xenlight_golang_define_enum(ty), [])
75
76 elif isinstance(ty, idl.Aggregate):
77 return xenlight_golang_define_struct(ty)
78
79 def xenlight_golang_define_enum(ty = None):
80 s = ''
81 typename = ''
82
83 if ty.typename is not None:
84 typename = xenlight_golang_fmt_name(ty.typename)
85 s += 'type {0} int\n'.format(typename)
86
87 # Start const block
88 s += 'const(\n'
89
90 for v in ty.values:
91 name = xenlight_golang_fmt_name(v.name)
92 s += '{0} {1} = {2}\n'.format(name, typename, v.value)
93
94 # End const block
95 s += ')\n'
96
97 return s
98
99 def xenlight_golang_define_struct(ty = None, typename = None, nested = False):
100 s = ''
101 extras = []
102 name = ''
103
104 if typename is not None:
105 name = xenlight_golang_fmt_name(typename)
106 else:
107 name = xenlight_golang_fmt_name(ty.typename)
108
109 # Begin struct definition
110 if nested:
111 s += '{0} struct {{\n'.format(name)
112 else:
113 s += 'type {0} struct {{\n'.format(name)
114
115 # Write struct fields
116 for f in ty.fields:
117 if f.type.typename is not None:
118 if isinstance(f.type, idl.Array):
119 typename = f.type.elem_type.typename
120 typename = xenlight_golang_fmt_name(typename)
121 name = xenlight_golang_fmt_name(f.name)
122
123 s += '{0} []{1}\n'.format(name, typename)
124 else:
125 typename = f.type.typename
126 typename = xenlight_golang_fmt_name(typename)
127 name = xenlight_golang_fmt_name(f.name)
128
129 s += '{0} {1}\n'.format(name, typename)
130
131 elif isinstance(f.type, idl.Struct):
132 r = xenlight_golang_define_struct(f.type, typename=f.name, nested=True)
133
134 s += r[0]
135 extras.extend(r[1])
136
137 elif isinstance(f.type, idl.KeyedUnion):
138 r = xenlight_golang_define_union(f.type, ty.typename, f.name)
139
140 s += r[0]
141 extras.extend(r[1])
142
143 else:
144 raise Exception('type {0} not supported'.format(f.type))
145
146 # End struct definition
147 s += '}\n'
148
149 return (s,extras)
150
151 def xenlight_golang_define_union(ty = None, struct_name = '', union_name = ''):
152 """
153 Generate the Go translation of a KeyedUnion.
154
155 Define an unexported interface to be used as
156 the type of the union. Then, define a struct
157 for each field of the union which implements
158 that interface.
159 """
160 s = ''
161 extras = []
162
163 interface_name = '{0}_{1}_union'.format(struct_name, ty.keyvar.name)
164 interface_name = xenlight_golang_fmt_name(interface_name)
165
166 s += 'type {0} interface {{\n'.format(interface_name)
167 s += 'is{0}()\n'.format(interface_name)
168 s += '}\n'
169
170 extras.append(s)
171
172 for f in ty.fields:
173 if f.type is None:
174 continue
175
176 # Define struct
177 name = '{0}_{1}_union_{2}'.format(struct_name, ty.keyvar.name, f.name)
178 r = xenlight_golang_define_struct(f.type, typename=name)
179 extras.append(r[0])
180 extras.extend(r[1])
181
182 # This typeof trick ensures that the fields used in the cgo struct
183 # used for marshaling are the same as the fields of the union in the
184 # actual C type, and avoids re-defining all of those fields.
185 s = 'typedef typeof(((struct {0} *)NULL)->{1}.{2}){3};'
186 s = s.format(struct_name, union_name, f.name, name)
187 cgo_helpers_preamble.append(s)
188
189 # Define function to implement 'union' interface
190 name = xenlight_golang_fmt_name(name)
191 s = 'func (x {0}) is{1}(){{}}\n'.format(name, interface_name)
192 extras.append(s)
193
194 fname = xenlight_golang_fmt_name(ty.keyvar.name)
195 ftype = xenlight_golang_fmt_name(ty.keyvar.type.typename)
196 s = '{0} {1}\n'.format(fname, ftype)
197
198 fname = xenlight_golang_fmt_name('{0}_union'.format(ty.keyvar.name))
199 s += '{0} {1}\n'.format(fname, interface_name)
200
201 return (s,extras)
202
203 def xenlight_golang_generate_helpers(path = None, types = None, comment = None):
204 """
205 Generate a .go file (helpers.gen.go by default)
206 that contains helper functions for marshaling between
207 C and Go types.
208 """
209 if path is None:
210 path = 'helpers.gen.go'
211
212 with open(path, 'w') as f:
213 if comment is not None:
214 f.write(comment)
215 f.write('package xenlight\n\n')
216 f.write('import (\n"unsafe"\n"errors"\n"fmt"\n)\n')
217
218 # Cgo preamble
219 f.write('/*\n')
220 f.write('#cgo LDFLAGS: -lxenlight\n')
221 f.write('#include <stdlib.h>\n')
222 f.write('#include <libxl.h>\n')
223 f.write('\n')
224
225 for s in cgo_helpers_preamble:
226 f.write(s)
227 f.write('\n')
228
229 f.write('*/\nimport "C"\n')
230
231 for ty in types:
232 if not isinstance(ty, idl.Struct):
233 continue
234
235 f.write(xenlight_golang_define_constructor(ty))
236 f.write('\n')
237
238 (fdef, extras) = xenlight_golang_define_from_C(ty)
239
240 f.write(fdef)
241 f.write('\n')
242
243 for extra in extras:
244 f.write(extra)
245 f.write('\n')
246
247 f.write(xenlight_golang_define_to_C(ty))
248 f.write('\n')
249
250 def xenlight_golang_define_from_C(ty = None):
251 """
252 Define the fromC marshaling function for the type
253 represented by ty.
254 """
255 func = 'func (x *{0}) fromC(xc *C.{1}) error {{\n {2}\n return nil}}\n'
256
257 goname = xenlight_golang_fmt_name(ty.typename)
258 cname = ty.typename
259
260 body = ''
261 extras = []
262
263 for f in ty.fields:
264 if f.type.typename is not None:
265 if isinstance(f.type, idl.Array):
266 body += xenlight_golang_array_from_C(f)
267 continue
268
269 body += xenlight_golang_convert_from_C(f)
270
271 elif isinstance(f.type, idl.Struct):
272 # Go through the fields of the anonymous nested struct.
273 for nf in f.type.fields:
274 body += xenlight_golang_convert_from_C(nf,outer_name=f.name)
275
276 elif isinstance(f.type, idl.KeyedUnion):
277 r = xenlight_golang_union_from_C(f.type, f.name, ty.typename)
278
279 body += r[0]
280 extras.extend(r[1])
281
282 else:
283 raise Exception('type {0} not supported'.format(f.type))
284
285 return (func.format(goname, cname, body), extras)
286
287 def xenlight_golang_convert_from_C(ty = None, outer_name = None, cvarname = None):
288 """
289 Returns a line of Go code that converts the C type represented
290 by ty to its corresponding Go type.
291
292 If outer_name is set, the type is treated as nested within another field
293 named outer_name.
294 """
295 s = ''
296
297 # Use 'xc' as the name for the C variable unless otherwise specified
298 if cvarname is None:
299 cvarname = 'xc'
300
301 gotypename = xenlight_golang_fmt_name(ty.type.typename)
302 goname = xenlight_golang_fmt_name(ty.name)
303 cname = ty.name
304
305 # In cgo, C names that conflict with Go keywords can be
306 # accessed by prepending an underscore to the name.
307 if cname in go_keywords:
308 cname = '_' + cname
309
310 # If outer_name is set, treat this as nested.
311 if outer_name is not None:
312 goname = '{0}.{1}'.format(xenlight_golang_fmt_name(outer_name), goname)
313 cname = '{0}.{1}'.format(outer_name, cname)
314
315 # Types that satisfy this condition can be easily casted or
316 # converted to a Go builtin type.
317 is_castable = (ty.type.json_parse_type == 'JSON_INTEGER' or
318 isinstance(ty.type, idl.Enumeration) or
319 gotypename in go_builtin_types)
320
321 if not is_castable:
322 # If the type is not castable, we need to call its fromC
323 # function.
324 s += 'if err := x.{0}.fromC(&{1}.{2});'.format(goname,cvarname,cname)
325 s += 'err != nil {{\nreturn fmt.Errorf("converting field {0}: %v", err)\n}}\n'.format(goname)
326
327 elif gotypename == 'string':
328 # Use the cgo helper for converting C strings.
329 s += 'x.{0} = C.GoString({1}.{2})\n'.format(goname,cvarname,cname)
330
331 else:
332 s += 'x.{0} = {1}({2}.{3})\n'.format(goname,gotypename,cvarname,cname)
333
334 return s
335
336 def xenlight_golang_union_from_C(ty = None, union_name = '', struct_name = ''):
337 extras = []
338
339 keyname = ty.keyvar.name
340 gokeyname = xenlight_golang_fmt_name(keyname)
341 keytype = ty.keyvar.type.typename
342 gokeytype = xenlight_golang_fmt_name(keytype)
343 field_name = xenlight_golang_fmt_name('{0}_union'.format(keyname))
344
345 interface_name = '{0}_{1}_union'.format(struct_name, keyname)
346 interface_name = xenlight_golang_fmt_name(interface_name)
347
348 cgo_keyname = keyname
349 if cgo_keyname in go_keywords:
350 cgo_keyname = '_' + cgo_keyname
351
352 cases = {}
353
354 for f in ty.fields:
355 val = '{0}_{1}'.format(keytype, f.name)
356 val = xenlight_golang_fmt_name(val)
357
358 # Add to list of cases to make for the switch
359 # statement below.
360 cases[f.name] = (val, f.type)
361
362 if f.type is None:
363 continue
364
365 # Define fromC func for 'union' struct.
366 typename = '{0}_{1}_union_{2}'.format(struct_name,keyname,f.name)
367 gotypename = xenlight_golang_fmt_name(typename)
368
369 # Define the function here. The cases for keyed unions are a little
370 # different.
371 s = 'func (x *{0}) fromC(xc *C.{1}) error {{\n'.format(gotypename,struct_name)
372 s += 'if {0}(xc.{1}) != {2} {{\n'.format(gokeytype,cgo_keyname,val)
373 err_string = '"expected union key {0}"'.format(val)
374 s += 'return errors.New({0})\n'.format(err_string)
375 s += '}\n\n'
376 s += 'tmp := (*C.{0})(unsafe.Pointer(&xc.{1}[0]))\n'.format(typename,union_name)
377
378 for nf in f.type.fields:
379 if isinstance(nf.type, idl.Array):
380 s += xenlight_golang_array_from_C(nf,cvarname='tmp')
381 continue
382
383 s += xenlight_golang_convert_from_C(nf,cvarname='tmp')
384
385 s += 'return nil\n'
386 s += '}\n'
387
388 extras.append(s)
389
390 s = 'x.{0} = {1}(xc.{2})\n'.format(gokeyname,gokeytype,cgo_keyname)
391 s += 'switch x.{0}{{\n'.format(gokeyname)
392
393 # Create switch statement to determine which 'union element'
394 # to populate in the Go struct.
395 for case_name, case_tuple in sorted(cases.items()):
396 (case_val, case_type) = case_tuple
397
398 s += 'case {0}:\n'.format(case_val)
399
400 if case_type is None:
401 s += "x.{0} = nil\n".format(field_name)
402 continue
403
404 gotype = '{0}_{1}_union_{2}'.format(struct_name,keyname,case_name)
405 gotype = xenlight_golang_fmt_name(gotype)
406 goname = '{0}_{1}'.format(keyname,case_name)
407 goname = xenlight_golang_fmt_name(goname,exported=False)
408
409 s += 'var {0} {1}\n'.format(goname, gotype)
410 s += 'if err := {0}.fromC(xc);'.format(goname)
411 s += 'err != nil {{\n return fmt.Errorf("converting field {0}: %v", err)\n}}\n'.format(goname)
412
413 s += 'x.{0} = &{1}\n'.format(field_name, goname)
414
415 # End switch statement
416 s += 'default:\n'
417 err_string = '"invalid union key \'%v\'", x.{0}'.format(gokeyname)
418 s += 'return fmt.Errorf({0})'.format(err_string)
419 s += '}\n'
420
421 return (s,extras)
422
423 def xenlight_golang_array_from_C(ty = None, cvarname = 'xc'):
424 """
425 Convert C array to Go slice using the method
426 described here:
427
428 https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices
429 """
430 s = ''
431
432 gotypename = xenlight_golang_fmt_name(ty.type.elem_type.typename)
433 goname = xenlight_golang_fmt_name(ty.name)
434 ctypename = ty.type.elem_type.typename
435 cname = ty.name
436 cslice = 'c{0}'.format(goname)
437 clenvar = ty.type.lenvar.name
438
439 s += 'x.{0} = nil\n'.format(goname)
440 s += 'if n := int({0}.{1}); n > 0 {{\n'.format(cvarname,clenvar)
441 s += '{0} := '.format(cslice)
442 s +='(*[1<<28]C.{0})(unsafe.Pointer({1}.{2}))[:n:n]\n'.format(ctypename, cvarname, cname)
443 s += 'x.{0} = make([]{1}, n)\n'.format(goname, gotypename)
444 s += 'for i, v := range {0} {{\n'.format(cslice)
445
446 is_enum = isinstance(ty.type.elem_type,idl.Enumeration)
447 if gotypename in go_builtin_types or is_enum:
448 s += 'x.{0}[i] = {1}(v)\n'.format(goname, gotypename)
449 else:
450 s += 'if err := x.{0}[i].fromC(&v); err != nil {{\n'.format(goname)
451 s += 'return fmt.Errorf("converting field {0}: %v", err) }}\n'.format(goname)
452
453 s += '}\n}\n'
454
455 return s
456
457 def xenlight_golang_define_to_C(ty = None, typename = None, nested = False):
458 """
459 Define the toC marshaling function for the type
460 represented by ty.
461 """
462 func = 'func (x *{0}) toC(xc *C.{1}) (err error){{{2}\n return nil\n }}\n'
463 body = ''
464
465 if ty.dispose_fn is not None:
466 body += 'defer func(){{\nif err != nil{{\nC.{0}(xc)}}\n}}()\n\n'.format(ty.dispose_fn)
467
468 goname = xenlight_golang_fmt_name(ty.typename)
469 cname = ty.typename
470
471 for f in ty.fields:
472 if f.type.typename is not None:
473 if isinstance(f.type, idl.Array):
474 body += xenlight_golang_array_to_C(f)
475 continue
476
477 body += xenlight_golang_convert_to_C(f)
478
479 elif isinstance(f.type, idl.Struct):
480 for nf in f.type.fields:
481 body += xenlight_golang_convert_to_C(nf, outer_name=f.name)
482
483 elif isinstance(f.type, idl.KeyedUnion):
484 body += xenlight_golang_union_to_C(f.type, f.name, ty.typename)
485
486 else:
487 raise Exception('type {0} not supported'.format(f.type))
488
489 return func.format(goname, cname, body)
490
491 def xenlight_golang_convert_to_C(ty = None, outer_name = None,
492 govarname = None, cvarname = None):
493 """
494 Returns a line of Go code that converts the Go type represented
495 by ty to its corresponding Go type.
496
497 If outer_name is set, the type is treated as nested within another field
498 named outer_name.
499 """
500 s = ''
501
502 # Use 'xc' as the name for the C variable unless otherwise specified.
503 if cvarname is None:
504 cvarname = 'xc'
505
506 # Use 'x' as the name for the Go variable unless otherwise specified.
507 if govarname is None:
508 govarname = 'x'
509
510 gotypename = xenlight_golang_fmt_name(ty.type.typename)
511 ctypename = ty.type.typename
512 goname = xenlight_golang_fmt_name(ty.name)
513 cname = ty.name
514
515 # In cgo, C names that conflict with Go keywords can be
516 # accessed by prepending an underscore to the name.
517 if cname in go_keywords:
518 cname = '_' + cname
519
520 # If outer_name is set, treat this as nested.
521 if outer_name is not None:
522 goname = '{0}.{1}'.format(xenlight_golang_fmt_name(outer_name), goname)
523 cname = '{0}.{1}'.format(outer_name, cname)
524
525 is_castable = (ty.type.json_parse_type == 'JSON_INTEGER' or
526 isinstance(ty.type, idl.Enumeration) or
527 gotypename in go_builtin_types)
528
529 if not is_castable:
530 s += 'if err := {0}.{1}.toC(&{2}.{3}); err != nil {{\n'.format(govarname,goname,
531 cvarname,cname)
532 s += 'return fmt.Errorf("converting field {0}: %v", err)\n}}\n'.format(goname)
533
534 elif gotypename == 'string':
535 # Use the cgo helper for converting C strings.
536 s += 'if {0}.{1} != "" {{\n'.format(govarname,goname)
537 s += '{0}.{1} = C.CString({2}.{3})}}\n'.format(cvarname,cname,
538 govarname,goname)
539
540 else:
541 s += '{0}.{1} = C.{2}({3}.{4})\n'.format(cvarname,cname,ctypename,
542 govarname,goname)
543
544 return s
545
546 def xenlight_golang_union_to_C(ty = None, union_name = '',
547 struct_name = ''):
548 keyname = ty.keyvar.name
549 gokeyname = xenlight_golang_fmt_name(keyname)
550 keytype = ty.keyvar.type.typename
551 gokeytype = xenlight_golang_fmt_name(keytype)
552
553 interface_name = '{0}_{1}_union'.format(struct_name, keyname)
554 interface_name = xenlight_golang_fmt_name(interface_name)
555
556 cgo_keyname = keyname
557 if cgo_keyname in go_keywords:
558 cgo_keyname = '_' + cgo_keyname
559
560
561 s = 'xc.{0} = C.{1}(x.{2})\n'.format(cgo_keyname,keytype,gokeyname)
562 s += 'switch x.{0}{{\n'.format(gokeyname)
563
564 # Create switch statement to determine how to populate the C union.
565 for f in ty.fields:
566 key_val = '{0}_{1}'.format(keytype, f.name)
567 key_val = xenlight_golang_fmt_name(key_val)
568
569 s += 'case {0}:\n'.format(key_val)
570
571 if f.type is None:
572 s += "break\n"
573 continue
574
575 cgotype = '{0}_{1}_union_{2}'.format(struct_name,keyname,f.name)
576 gotype = xenlight_golang_fmt_name(cgotype)
577
578 field_name = xenlight_golang_fmt_name('{0}_union'.format(keyname))
579 s += 'tmp, ok := x.{0}.(*{1})\n'.format(field_name,gotype)
580 s += 'if !ok {\n'
581 s += 'return errors.New("wrong type for union key {0}")\n'.format(keyname)
582 s += '}\n'
583
584 s += 'var {0} C.{1}\n'.format(f.name,cgotype)
585 for uf in f.type.fields:
586 if isinstance(uf.type, idl.Array):
587 s += xenlight_golang_array_to_C(uf, cvarname=f.name,
588 govarname="tmp")
589 continue
590
591 s += xenlight_golang_convert_to_C(uf,cvarname=f.name,
592 govarname='tmp')
593
594 # The union is still represented as Go []byte.
595 s += '{0}Bytes := C.GoBytes(unsafe.Pointer(&{1}),C.sizeof_{2})\n'.format(f.name,
596 f.name,
597 cgotype)
598 s += 'copy(xc.{0}[:],{1}Bytes)\n'.format(union_name,f.name)
599
600 # End switch statement
601 s += 'default:\n'
602 err_string = '"invalid union key \'%v\'", x.{0}'.format(gokeyname)
603 s += 'return fmt.Errorf({0})'.format(err_string)
604 s += '}\n'
605
606 return s
607
608 def xenlight_golang_array_to_C(ty = None, cvarname="xc", govarname="x"):
609 s = ''
610
611 gotypename = xenlight_golang_fmt_name(ty.type.elem_type.typename)
612 goname = xenlight_golang_fmt_name(ty.name)
613 ctypename = ty.type.elem_type.typename
614 cname = ty.name
615 clenvar = ty.type.lenvar.name
616 golenvar = xenlight_golang_fmt_name(clenvar,exported=False)
617
618 is_enum = isinstance(ty.type.elem_type,idl.Enumeration)
619 if gotypename in go_builtin_types or is_enum:
620 s += 'if {0} := len({1}.{2}); {3} > 0 {{\n'.format(golenvar,govarname,goname,golenvar)
621 s += '{0}.{1} = (*C.{2})(C.malloc(C.size_t({3}*{4})))\n'.format(cvarname,cname,ctypename,
622 golenvar,golenvar)
623 s += '{0}.{1} = C.int({2})\n'.format(cvarname,clenvar,golenvar)
624 s += 'c{0} := (*[1<<28]C.{1})(unsafe.Pointer({2}.{3}))[:{4}:{5}]\n'.format(goname,
625 ctypename,cvarname,cname,
626 golenvar,golenvar)
627 s += 'for i,v := range {0}.{1} {{\n'.format(govarname,goname)
628 s += 'c{0}[i] = C.{1}(v)\n'.format(goname,ctypename)
629 s += '}\n}\n'
630
631 return s
632
633 s += 'if {0} := len({1}.{2}); {3} > 0 {{\n'.format(golenvar,govarname,goname,golenvar)
634 s += '{0}.{1} = (*C.{2})(C.malloc(C.ulong({3})*C.sizeof_{4}))\n'.format(cvarname,cname,ctypename,
635 golenvar,ctypename)
636 s += '{0}.{1} = C.int({2})\n'.format(cvarname,clenvar,golenvar)
637 s += 'c{0} := (*[1<<28]C.{1})(unsafe.Pointer({2}.{3}))[:{4}:{5}]\n'.format(goname,
638 ctypename,cvarname,cname,
639 golenvar,golenvar)
640 s += 'for i,v := range {0}.{1} {{\n'.format(govarname,goname)
641 s += 'if err := v.toC(&c{0}[i]); err != nil {{\n'.format(goname)
642 s += 'return fmt.Errorf("converting field {0}: %v", err)\n'.format(goname)
643 s += '}\n}\n}\n'
644
645 return s
646
647 def xenlight_golang_define_constructor(ty = None):
648 s = ''
649
650 ctypename = ty.typename
651 gotypename = xenlight_golang_fmt_name(ctypename)
652
653 # Since this func is exported, add a comment as per Go conventions.
654 s += '// New{0} returns an instance of {1}'.format(gotypename,gotypename)
655 s += ' initialized with defaults.\n'
656
657 # If a struct has a keyed union, an extra argument is
658 # required in the function signature, and an extra _init
659 # call is needed.
660 params = []
661 init_fns = []
662
663 # Add call to parent init_fn first.
664 init_fns.append('C.{0}(&xc)'.format(ty.init_fn))
665
666 for f in ty.fields:
667 if not isinstance(f.type, idl.KeyedUnion):
668 continue
669
670 param = f.type.keyvar
671
672 param_ctype = param.type.typename
673 param_gotype = xenlight_golang_fmt_name(param_ctype)
674 param_goname = xenlight_golang_fmt_name(param.name,exported=False)
675
676 # Serveral keyed unions use 'type' as the key variable name. In
677 # that case, prepend the first letter of the Go type name.
678 if param_goname == 'type':
679 param_goname = '{0}type'.format(param_gotype.lower()[0])
680
681 # Add call to keyed union's init_fn.
682 init_fns.append('C.{0}_{1}(&xc, C.{2}({3}))'.format(ty.init_fn,
683 param.name,
684 param_ctype,
685 param_goname))
686
687 # Add to params list.
688 params.append('{0} {1}'.format(param_goname, param_gotype))
689
690 # Define function
691 s += 'func New{0}({1}) (*{2}, error) {{\n'.format(gotypename,
692 ','.join(params),
693 gotypename)
694
695 # Declare variables.
696 s += 'var (\nx {0}\nxc C.{1})\n\n'.format(gotypename, ctypename)
697
698 # Write init_fn calls.
699 s += '\n'.join(init_fns)
700 s += '\n'
701
702 # Make sure dispose_fn get's called when constructor
703 # returns.
704 if ty.dispose_fn is not None:
705 s += 'defer C.{0}(&xc)\n'.format(ty.dispose_fn)
706
707 s += '\n'
708
709 # Call fromC to initialize Go type.
710 s += 'if err := x.fromC(&xc); err != nil {\n'
711 s += 'return nil, err }\n\n'
712 s += 'return &x, nil}\n'
713
714 return s
715
716 def xenlight_golang_fmt_name(name, exported = True):
717 """
718 Take a given type name and return an
719 appropriate Go type name.
720 """
721 if name in builtin_type_names.keys():
722 return builtin_type_names[name]
723
724 # Name is not a builtin, format it for Go.
725 words = name.split('_')
726
727 # Remove 'libxl' prefix
728 if words[0].lower() == 'libxl':
729 words.remove(words[0])
730
731 if exported:
732 return ''.join(x.title() for x in words)
733
734 return words[0] + ''.join(x.title() for x in words[1:])
735
736 if __name__ == '__main__':
737 if len(sys.argv) != 4:
738 print("Usage: gengotypes.py <idl> <types.gen.go> <helpers.gen.go>", file=sys.stderr)
739 sys.exit(1)
740
741 idlname = sys.argv[1]
742 path_types = sys.argv[2]
743 path_helpers = sys.argv[3]
744
745 (builtins, types) = idl.parse(idlname)
746
747 for b in builtins:
748 name = b.typename
749 builtin_type_names[name] = xenlight_golang_fmt_name(name)
750
751 header_comment="""// Code generated by {}. DO NOT EDIT.
752 // source: {}
753
754 """.format(os.path.basename(sys.argv[0]),
755 os.path.basename(sys.argv[1]))
756
757 xenlight_golang_generate_types(types=types,
758 path=path_types,
759 comment=header_comment)
760 xenlight_golang_generate_helpers(types=types,
761 path=path_helpers,
762 comment=header_comment)