forked from xlab/c-for-go
/
gen_struct_helpers.go
362 lines (333 loc) · 11.2 KB
/
gen_struct_helpers.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
package generator
import (
"bytes"
"fmt"
"hash/crc32"
tl "github.com/digitalocean-labs/c-for-go/translator"
)
func (gen *Generator) getStructHelpers(goStructName []byte, cStructName string, spec tl.CType) (helpers []*Helper) {
crc := getRefCRC(spec)
cgoSpec := gen.tr.CGoSpec(spec, true)
buf := new(bytes.Buffer)
fmt.Fprintf(buf, "func (x *%s) Ref() *%s", goStructName, cgoSpec)
fmt.Fprintf(buf, `{
if x == nil {
return nil
}
return x.ref%2x
}`, crc)
helpers = append(helpers, &Helper{
Name: fmt.Sprintf("%s.Ref", goStructName),
Description: "Ref returns the underlying reference to C object or nil if struct is nil.",
Source: buf.String(),
})
buf.Reset()
fmt.Fprintf(buf, "func (x *%s) Free()", goStructName)
fmt.Fprintf(buf, `{
if x != nil && x.allocs%2x != nil {
x.allocs%2x.(*cgoAllocMap).Free()
x.ref%2x = nil
}
}`, crc, crc, crc)
helpers = append(helpers, &Helper{
Name: fmt.Sprintf("%s.Free", goStructName),
Description: "Free invokes alloc map's free mechanism that cleanups any allocated memory using C free.\n" +
"Does nothing if struct is nil or has no allocation map.",
Source: buf.String(),
})
buf.Reset()
fmt.Fprintf(buf, "func New%sRef(ref unsafe.Pointer) *%s", goStructName, goStructName)
fmt.Fprintf(buf, `{
if ref == nil {
return nil
}
obj := new(%s)
obj.ref%2x = (*%s)(unsafe.Pointer(ref))
return obj
}`, goStructName, crc, cgoSpec)
name := fmt.Sprintf("New%sRef", goStructName)
helpers = append(helpers, &Helper{
Name: name,
Description: name + " creates a new wrapper struct with underlying reference set to the original C object.\n" +
"Returns nil if the provided pointer to C object is nil too.",
Source: buf.String(),
})
buf.Reset()
fmt.Fprintf(buf, "func (x *%s) PassRef() (*%s, *cgoAllocMap) {\n", goStructName, cgoSpec)
buf.Write(gen.getPassRefSource(goStructName, cStructName, spec))
buf.WriteRune('}')
helpers = append(helpers, &Helper{
Name: fmt.Sprintf("%s.PassRef", goStructName),
Description: "PassRef returns the underlying C object, otherwise it will allocate one and set its values\n" +
"from this wrapping struct, counting allocations into an allocation map.",
Source: buf.String(),
})
buf.Reset()
fmt.Fprintf(buf, "func (x %s) PassValue() (%s, *cgoAllocMap) {\n", goStructName, cgoSpec)
buf.Write(gen.getPassValueSource(goStructName, spec))
buf.WriteRune('}')
helpers = append(helpers, &Helper{
Name: fmt.Sprintf("%s.PassValue", goStructName),
Description: "PassValue does the same as PassRef except that it will try to dereference the returned pointer.",
Source: buf.String(),
})
buf.Reset()
fmt.Fprintf(buf, "func (x *%s) Deref() {\n", goStructName)
buf.Write(gen.getDerefSource(goStructName, cStructName, spec))
buf.WriteRune('}')
helpers = append(helpers, &Helper{
Name: fmt.Sprintf("%s.Deref", goStructName),
Description: "Deref uses the underlying reference to C object and fills the wrapping struct with values.\n" +
"Do not forget to call this method whether you get a struct for C object and want to read its values.",
Source: buf.String(),
})
return
}
func (gen *Generator) getRawStructHelpers(goStructName []byte, cStructName string, spec tl.CType) (helpers []*Helper) {
if spec.GetPointers() > 0 {
return nil // can't addess a pointer receiver
}
cgoSpec := gen.tr.CGoSpec(spec, true)
structSpec := spec.(*tl.CStructSpec)
buf := new(bytes.Buffer)
fmt.Fprintf(buf, "func (x *%s) Ref() *%s", goStructName, cgoSpec)
fmt.Fprintf(buf, `{
if x == nil {
return nil
}
return (*%s)(unsafe.Pointer(x))
}`, cgoSpec)
helpers = append(helpers, &Helper{
Name: fmt.Sprintf("%s.Ref", goStructName),
Description: "Ref returns a reference to C object as it is.",
Source: buf.String(),
})
buf.Reset()
fmt.Fprintf(buf, "func (x *%s) Free()", goStructName)
fmt.Fprint(buf, `{
if x != nil {
C.free(unsafe.Pointer(x))
}
}`)
helpers = append(helpers, &Helper{
Name: fmt.Sprintf("%s.Free", goStructName),
Description: "Free cleanups the referenced memory using C free.",
Source: buf.String(),
})
buf.Reset()
fmt.Fprintf(buf, "func New%sRef(ref unsafe.Pointer) *%s", goStructName, goStructName)
fmt.Fprintf(buf, `{
return (*%s)(ref)
}`, goStructName)
name := fmt.Sprintf("New%sRef", goStructName)
helpers = append(helpers, &Helper{
Name: name,
Description: name + " converts the C object reference into a raw struct reference without wrapping.",
Source: buf.String(),
})
buf.Reset()
allocHelper := gen.getAllocMemoryHelper(cgoSpec)
fmt.Fprintf(buf, "func New%s() *%s", goStructName, goStructName)
fmt.Fprintf(buf, `{
return (*%s)(%s(1))
}`, goStructName, allocHelper.Name)
name = fmt.Sprintf("New%s", goStructName)
helpers = append(helpers, &Helper{
Name: name,
Description: name + " allocates a new C object of this type and converts the reference into\n" +
"a raw struct reference without wrapping.",
Source: buf.String(),
Requires: []*Helper{allocHelper},
})
buf.Reset()
fmt.Fprintf(buf, "func (x *%s) PassRef() *%s", goStructName, cgoSpec)
fmt.Fprintf(buf, `{
if x == nil {
x = (*%s)(%s(1))
}
return (*%s)(unsafe.Pointer(x))
}`, goStructName, allocHelper.Name, cgoSpec)
helpers = append(helpers, &Helper{
Name: fmt.Sprintf("%s.PassRef", goStructName),
Description: "PassRef returns a reference to C object as it is or allocates a new C object of this type.",
Source: buf.String(),
Requires: []*Helper{allocHelper},
})
if !gen.cfg.Options.StructAccessors {
return
}
ptrTipRx, typeTipRx, memTipRx := gen.tr.TipRxsForSpec(tl.TipScopeType, cStructName, spec)
for i, m := range structSpec.Members {
if len(m.Name) == 0 {
continue
}
buf.Reset()
typeName := m.Spec.GetBase()
switch m.Spec.Kind() {
case tl.StructKind, tl.OpaqueStructKind, tl.UnionKind, tl.EnumKind:
if !gen.tr.IsAcceptableName(tl.TargetType, typeName) {
continue
}
}
memTip := memTipRx.TipAt(i)
if !memTip.IsValid() {
memTip = gen.MemTipOf(m)
}
ptrTip := ptrTipRx.TipAt(i)
if memTip == tl.TipMemRaw {
ptrTip = tl.TipPtrSRef
}
typeTip := typeTipRx.TipAt(i)
goSpec := gen.tr.TranslateSpec(m.Spec, ptrTip, typeTip)
cgoSpec := gen.tr.CGoSpec(m.Spec, false)
// does not work for function pointers
if goSpec.Pointers > 0 && goSpec.Base == "func" {
continue
}
const public = true
goName := string(gen.tr.TransformName(tl.TargetType, m.Name, public))
arr := len(goSpec.OuterArr.Sizes()) > 0 || len(goSpec.InnerArr.Sizes()) > 0
if !arr {
goSpec.Pointers += 1
cgoSpec.Pointers += 1
}
fmt.Fprintf(buf, "func (s *%s) Get%s() %s {\n", goStructName, goName, goSpec)
lenField := getLenField(gen, structSpec, m)
toProxy, _ := gen.proxyValueToGo(memTip, "ret", "&s."+m.Name, goSpec, cgoSpec, lenField)
fmt.Fprintf(buf, "\tvar ret %s\n", goSpec)
fmt.Fprintf(buf, "\t%s\n", toProxy)
fmt.Fprintf(buf, "\treturn ret\n")
fmt.Fprintf(buf, "}\n")
helpers = append(helpers, &Helper{
Name: fmt.Sprintf("%s.Get%s", goStructName, goName),
Description: fmt.Sprintf("Get%s returns a reference to C object within a struct", goName),
Source: buf.String(),
})
}
return
}
func (gen *Generator) getPassRefSource(goStructName []byte, cStructName string, spec tl.CType) []byte {
cgoSpec := gen.tr.CGoSpec(spec, false)
structSpec := spec.(*tl.CStructSpec)
buf := new(bytes.Buffer)
crc := getRefCRC(spec)
fmt.Fprintf(buf, `if x == nil {
return nil, nil
} else if x.ref%2x != nil {
return x.ref%2x, nil
}`, crc, crc)
writeSpace(buf, 1)
h := gen.getAllocMemoryHelper(tl.CGoSpec{Base: cgoSpec.Base})
gen.submitHelper(h)
fmt.Fprintf(buf, "mem%2x := %s(1)\n", crc, h.Name)
fmt.Fprintf(buf, "ref%2x := (*%s)(mem%2x)\n", crc, cgoSpec.Base, crc)
fmt.Fprintf(buf, "allocs%2x := new(cgoAllocMap)\n", crc)
fmt.Fprintf(buf, "allocs%2x.Add(mem%2x)\n", crc, crc)
writeSpace(buf, 1)
ptrTipRx, typeTipRx, memTipRx := gen.tr.TipRxsForSpec(tl.TipScopeType, cStructName, spec)
for i, m := range structSpec.Members {
if len(m.Name) == 0 {
continue
// TODO: generate setters
}
typeName := m.Spec.GetBase()
switch m.Spec.Kind() {
case tl.StructKind, tl.OpaqueStructKind, tl.UnionKind, tl.EnumKind:
if !gen.tr.IsAcceptableName(tl.TargetType, typeName) {
continue
}
}
memTip := memTipRx.TipAt(i)
if !memTip.IsValid() {
memTip = gen.MemTipOf(m)
}
ptrTip := ptrTipRx.TipAt(i)
if memTip == tl.TipMemRaw {
ptrTip = tl.TipPtrSRef
}
typeTip := typeTipRx.TipAt(i)
goSpec := gen.tr.TranslateSpec(m.Spec, ptrTip, typeTip)
cgoSpec := gen.tr.CGoSpec(m.Spec, false)
const public = true
goName := "x." + string(gen.tr.TransformName(tl.TargetType, m.Name, public))
fromProxy, nillable := gen.proxyValueFromGo(memTip, goName, goSpec, cgoSpec)
if nillable {
fmt.Fprintf(buf, "if %s != nil {\n", goName)
}
fmt.Fprintf(buf, "var c%s_allocs *cgoAllocMap\n", m.Name)
fmt.Fprintf(buf, "ref%2x.%s, c%s_allocs = %s\n", crc, m.Name, m.Name, fromProxy)
fmt.Fprintf(buf, "allocs%2x.Borrow(c%s_allocs)\n", crc, m.Name)
if nillable {
fmt.Fprintf(buf, "}\n\n")
} else {
fmt.Fprint(buf, "\n")
}
}
fmt.Fprintf(buf, "x.ref%2x = ref%2x\n", crc, crc)
fmt.Fprintf(buf, "x.allocs%2x = allocs%2x\n", crc, crc)
fmt.Fprintf(buf, "return ref%2x, allocs%2x\n", crc, crc)
writeSpace(buf, 1)
return buf.Bytes()
}
func (gen *Generator) getPassValueSource(goStructName []byte, spec tl.CType) []byte {
buf := new(bytes.Buffer)
crc := getRefCRC(spec)
fmt.Fprintf(buf, `if x.ref%2x != nil {
return *x.ref%2x, nil
}`, crc, crc)
writeSpace(buf, 1)
fmt.Fprintf(buf, "ref, allocs := x.PassRef()\n")
fmt.Fprintf(buf, "return *ref, allocs\n")
return buf.Bytes()
}
func getRefCRC(spec tl.CType) uint32 {
return crc32.ChecksumIEEE([]byte(spec.String()))
}
func (gen *Generator) getDerefSource(goStructName []byte, cStructName string, spec tl.CType) []byte {
structSpec := spec.(*tl.CStructSpec)
buf := new(bytes.Buffer)
crc := getRefCRC(spec)
fmt.Fprintf(buf, `if x.ref%2x == nil {
return
}`, crc)
writeSpace(buf, 1)
ptrTipRx, typeTipRx, memTipRx := gen.tr.TipRxsForSpec(tl.TipScopeType, cStructName, spec)
for i, m := range structSpec.Members {
if len(m.Name) == 0 {
continue
// TODO: generate getters
}
typeName := m.Spec.GetBase()
switch m.Spec.Kind() {
case tl.StructKind, tl.OpaqueStructKind, tl.UnionKind, tl.EnumKind:
if !gen.tr.IsAcceptableName(tl.TargetType, typeName) {
continue
}
}
memTip := memTipRx.TipAt(i)
if !memTip.IsValid() {
memTip = gen.MemTipOf(m)
}
ptrTip := ptrTipRx.TipAt(i)
if memTip == tl.TipMemRaw {
ptrTip = tl.TipPtrSRef
}
typeTip := typeTipRx.TipAt(i)
goSpec := gen.tr.TranslateSpec(m.Spec, ptrTip, typeTip)
const public = true
goName := "x." + string(gen.tr.TransformName(tl.TargetType, m.Name, public))
cgoName := fmt.Sprintf("x.ref%2x.%s", crc, m.Name)
cgoSpec := gen.tr.CGoSpec(m.Spec, false)
lenField := getLenField(gen, structSpec, m)
toProxy, _ := gen.proxyValueToGo(memTip, goName, cgoName, goSpec, cgoSpec, lenField)
fmt.Fprintln(buf, toProxy)
}
return buf.Bytes()
}
func getLenField(gen *Generator, structSpec *tl.CStructSpec, m *tl.CDecl) string {
lenField := ""
if gen.tr.LenFields() != nil {
lenField = gen.tr.LenFields()[structSpec.Typedef+"."+m.Name]
}
return lenField
}